Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing and Accessing nested REST API Urls

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading