Home > Software engineering >  Post to api with parameters
Post to api with parameters

Time:10-15

Trying to call an api :"https://api.postcodes.io/postcodes/" Is a post-call with this structure:

{
  "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"]
}

What is the best practice to create the array of postcodes and how to send them? My code:

List<string> test = new List<string>();
test.Add("OX49 5NU");
test.Add("M32 0JG");
test.Add("NE30 1DP");

var requestString = string.Join(",", test.ToArray());

var queryParams = new Dictionary<string, string>()
{
    { "postcodes", requestString }
};

var s = queryParams.ToString();
var data = new StringContent(queryParams.ToString(), Encoding.UTF8, "application/json");
var uri = "https://api.postcodes.io/postcodes/";
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(uri, data);

Not working.

Kind regards /Rudy

CodePudding user response:

You shouldn't be using .ToString() at all and rely on the wonderful JSON serialization available in .Net.

    List<string> postcodes = new List<string>
    {
        "OX49 5NU",
        "M32 0JG",
        "NE30 1DP"
    };

    var json = System.Text.Json.JsonSerializer.Serialize(new { postcodes });
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    
    using var httpClient = new HttpClient();

    var uri = "https://api.postcodes.io/postcodes/";
    var response = await httpClient.PostAsync(uri, content);

new { postcodes } creates an anonymous type with a single property named postcodes consisting of the list of postcodes.

Note also the using on httpClient. For a trivial example it probably doesn't matter but you should at least be disposing of the httpClient properly.

UPDATE
As @marsze pointed out, it's usually best to use IHttpClientFactory, calling CreateClient() when you need a HttpClient this will allow .Net to pool HttpClients that can be reused without consuming additional resources.

CodePudding user response:

Your request has to be in JSON format. For that, you might want to write your own DTO, somewhat like this:

class PostcodeBody
{
    public List<string> Postcodes { get; } = new List<string>();
}

And then serialize it using the JSON serializer of your choice:

var body = new PostcodeBody();
body.Postcodes.Add("OX49 5NU");
body.Postcodes.Add("M32 0JG");
body.Postcodes.Add("NE30 1DP");
var data = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
  • Related