Home > OS >  How to consume an API via OData protocol in .Net Core?
How to consume an API via OData protocol in .Net Core?

Time:07-18

I'm trying to consume a public endpoint to get a list of objects in json. However, the API implements the OData protocol, and it always returns an invalid request. I think it's due to the way of calling this API. What should I adapt to my code to consume this API?

This is my code:

[HttpGet]
public async Task<List<TaxaSelic>> ObterTaxaSelic()
{
    List<TaxaSelic> taxasSelic = new List<TaxaSelic>();
    string apiResponse = string.Empty;

    Uri uri = new Uri("https://api.bcb.gov.br/dados/serie/bcdata.sgs.4390/dados/ultimos/10/");

    using (HttpClient httpClient = new HttpClient())
    {
        using (HttpResponseMessage response = await httpClient.GetAsync(uri))
        {
            if (response.IsSuccessStatusCode)
                apiResponse = await response.Content.ReadAsStringAsync();

            taxasSelic = JsonConvert.DeserializeObject<List<TaxaSelic>>(apiResponse);
        }
    }

    return taxasSelic;
}

and...

public class TaxaSelic : Entity
{
    [JsonProperty("data")]
    public string Data { get; set; }

    [JsonProperty("valor")]
    public string Valor { get; set; }
}

CodePudding user response:

The website's server in some way checks the caller's user-agent. When I set a user-agent as following, it works like a charm.

using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Linux; Android 9; SM-G973U Build/PPR1.180610.011) "  
                                                               "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile "  
                                                               "Safari/537.36");
            using (HttpResponseMessage response = await httpClient.GetAsync(uri))
            { 

 ... rest of your code
 .
 .
 .

Example output I got,

HTTP/1.1 200 OK
ETag: W/"173-8/kblablablaMdY/QZ9jQ"
Access-Control-Allow-Origin: *
Date: Mon, 18 Jul 2022 11:48:19 GMT
Set-Cookie: cookie_p=!ptxb5qIxn7aCp0blablablablaTOUoak=; path=/; Httponly; Secure
Set-Cookie: TS01799025=01blablablacae675f; Path=/
Strict-Transport-Security: max-age=16070400; includeSubDomains
Content-Type: application/json; charset=utf-8
Content-Length: 371

[{"data":"01/10/2021","valor":"0.49"},{"data":"01/11/2021","valor":"0.59"},{"data":"01/12/2021","valor":"0.77"},{"data":"01/01/2022","valor":"0.73"},{"data":"01/02/2022","valor":"0.76"},{"data":"01/03/2022","valor":"0.93"},{"data":"01/04/2022","valor":"0.83"},{"data":"01/05/2022","valor":"1.03"},{"data":"01/06/2022","valor":"1.02"},{"data":"01/07/2022","valor":"0.54"}]
  • Related