Home > Blockchain >  Storing and Accessing nested REST API Urls
Storing and Accessing nested REST API Urls

Time:11-18

I am working with a REST API, and I want to be able to efficiently store and access nested URL strings.

My ideal would be to be able to type something like myHttpClient.PostAsync(url.things.search, mycontent) and have that execute at runtime as myHttpClient.PostAsync("myurl.com/thethingsiwant/searchingthethings", mycontent), or type myHttpClient.PostAsync(url.things.create, mycontent) and resolve it as myHttpClient.PostAsync("myurl.com/thethingsiwant/creatingathing", mycontent), with there being multiple levels and branches of strings listed.

I looked at potentially using a dictionary, but that doesn't give me the clean access to the "." operator that I want and doesn't nest as cleanly either. Enums were likewise unsuitable for my needs, from what I read.

I realize I can create a custom class that will do what I want, but I feel like there should be some data structure that can do what I want more easily, and I just can't quite figure out the right terms to google to find it.

What would be the best way for me to go about making this nested structure of strings?

Thank you!

CodePudding user response:

I'm not sure I fully understand what you're asking, but you might try creating an instance of HttpClientFactory (assuming you are on .NET Core 2 or later) with a base url.

In Startup.cs, you'd add:

public void ConfigureServices(IServiceCollection services)
{
    . . .
    services.AddHttpClient("url.things", c =>
    {
        c.BaseAddress = new Uri("http://myurl.com/thethingsiwant");
    });
    . . .
}

Then you'd inject this into your class:

private readonly IHttpClientFactory _clientFactory;

public MyService(IHttpClientFactory clientFactory)
{
    _clientFactory = clientFactory;
}

And you'd call it this way:

var myHttpClient = _clientFactory.CreateClient("url.things");
myHttpClient.PostAsync("creatingathing", mycontent);

I believe this would work with PostAsync, but I'm not 100% sure. I normally use SendAsync and create an HttpRequestMessage, so results may vary.

  • Related