How to Make Calls to a Rest API Using C#

How do I make calls to a REST API using C#?

The ASP.NET Web API has replaced the WCF Web API previously mentioned.

I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".

Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.

Here's how your example would look when implemented using the ASP.NET Web API Client Library:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleProgram
{
public class DataObject
{
public string Name { get; set; }
}

public class Class1
{
private const string URL = "https://sub.domain.com/objects.json";
private string urlParameters = "?api_key=123";

static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);

// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Name);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}

// Make any other calls using HttpClient here.

// Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
client.Dispose();
}
}
}

If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?

For more details, including other examples, see Call a Web API From a .NET Client (C#)

This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services

Calling a Rest-API using C#

So, you can try out using HttpClient to call another API. Ex. https://docs.microsoft.com/ru-ru/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0 . And you can use libraries for that like Refit https://github.com/reactiveui/refit

edit: Link in english
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0

calling rest api on client side c#

First of all use

client.GetStringAsync(url).Result

instead of

client.GetStringAsync(url)

Second after you received the json, it becomes very simple to parse the result. I saw the previous answeres and they were all using a loop, which is not a good idea in my opinion to parse.
Use Newtonsoft.Json library and its very handy in such situations. I've parsed your json response using this library.
Make a class of result, i.e.

    public class result
{
public string name { get; set; }
public string alpha3_code { get; set; }
public string alpha2_code { get; set; }
}

put this code after getting json response for parsing your json.

JObject jsonResponse = JObject.Parse(jsonString);
JObject objResponse = (JObject)jsonResponse["RestResponse"];
Dictionary<string, JArray> _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString());
var results = _Data["result"].ToObject<List<result>>();

It works perfectly, I've tested this.

Don't forget to add Newtonsoft.Json AND Newtonsoft.Json.Linq namespaces

How to call Rest API with Content and Headers in c#?

Here a sample I use in one of my apps:

_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl), 
Timeout = new TimeSpan(0, 0, 0, 0, -1) };

_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");

Making a sequence of async API calls to an external provider

Given each async Task is awaited, your code will run sequentially. However, based on the code it seems you could execute the upload tasks concurrently (see example below).

Example showing how you could execute the uploads concurrently:

var client = await clientRepository.FirstOrDefaultAsync(c => c.UserId == userId);
if (client == null)
throw new ApiException("Failed to read client");

// Send data to provider
var applicant = await apiClient.CreateApplicantAsync(client);
if (applicant == null || applicant.Id.IsNullOrEmpty())
throw new ApiException("Failed to create applicant");

// Send files a to provider
var docUploadA = apiClient.UploadDocumentAsync(applicant.Id, dto.DocumentA.Stream, dto.DocumentA.FileName, dto.DocumentA.Document.Type);
var docUploadB = apiClient.UploadDocumentAsync(applicant.Id, dto.DocumentB.Stream, dto.DocumentB.FileName, dto.DocumentB.Document.Type);
var imageUpload = apiClient.UploadApplicantImageAsync(applicant.Id, dto.DocumentC.Stream, dto.DocumentC.FileName);
await Task.WhenAll(docUploadA, docUploadB, imageUpload);
if (docUploadA.Result == null || docUploadB.Result == null || imageUpload.Result == null)
throw new ApiException("Failed to upload document");

// Check the applicant
var checkResponse = await apiClient.CheckApplicantAsync(applicant.Id);
if (checkResponse == null)
throw new ApiException("Applicant check failed");

// Check is successful when the Result property is null
if (checkResponse.Result.IsNullOrEmpty())
{
result.Success();
}

Calling a REST API with C# ASP.NET MVC

The exception says it all:

Look at the exception

The model item passed into the dictionary is of type 'EdamaAPI.Models.Recipe', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[EdamaAPI.Models.Ingredient]'.

Look at the model:

@model IEnumerable<EdamaAPI.Models.Recipe>

You pass a recipe model to the view while the view required ingredient model.

This will work:

public class RecipeController : Controller
{

public async Task<ActionResult> Index()
{
List<Ingredient> RecInfo = new List<Ingredient>();

using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri("https://api.edamam.com");

client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api.edamam.com/search?q=chicken&app_id=a88093f8&app_key=4513de36c431f9936462ef4391f631e4&from=0&to=3&calories=gte%20591,%20lte%20722&health=alcohol-free");

//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var name = Res.Content.ReadAsStringAsync().Result;

//Deserializing the response recieved from web api and storing into the Employee list
RecInfo = JsonConvert.DeserializeObject<List<Ingredient>>(name);

}
//returning the employee list to view
return View(RecInfo);
}
}
}

but that's not what you need, as you need recipe model.
Change your action to accept a generic Recipe list.



Related Topics



Leave a reply



Submit