Miguel Moura
Miguel Moura

Reputation: 39354

Get response in JSON from API

I am using HttpClient to consume an external API from an ASP.NET Web API controller. I am not using authentication, just a token, so I have:

using (var httpClient = new HttpClient()) {

  httpClient.DefaultRequestHeaders.Accept.Clear();

  httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

  HttpResponseMessage response = await httpClient.GetAsync(endpoint);

}

I am getting the response always in XML format but I am sending header with "application/json".

Am I missing something it this is a problem with the external API?

What else can I try to get the response in JSON?

Upvotes: 0

Views: 1906

Answers (2)

IrvineCAGuy
IrvineCAGuy

Reputation: 211

You should set Accept: application/json as well as Content-Type: application/json.

Upvotes: -1

neverendingqs
neverendingqs

Reputation: 4276

It's up to the API developer(s) to respect the media type (application/json). It is possible for a developer to explicitly return XML when a client requests JSON (if they feel like trolling), though in this case it is probably just giving you the default format because they don't check the header value.

Check the docs or contact them directly to confirm they return data in JSON format and how to format the request to get JSON.

Upvotes: 2

Related Questions