I am building .NET 5 core with mvc application in which i need to access third party API in an .NET Core RestSharp makes the call to the 3rd party Web API.In the end of this blog I will address this types of question like as how to call third party rest api in c#?how to call external api in c#?how to call third party api in web api?how to call third party api in .net core?how to use third party api using RestSharp?how to get third party api response in c#?call web api from c# ?code behind?how to consume rest api in c#.
Download Source code : https://findandsolve.com/source-code/code-consume-web-api-in-dot-net-5-core-source-code
REST client
REST relies on client-server relationship and provides a uniform interface between components.The most simple task-based async, strongly typed, cross-platform . NET REST Client. RestClient.Net is a REST client framework built in C# .NET based cross-platform project.The REST service API that is exposed for communication by any system or service provider.RESTful services uses HTTP (Hyper Text Transfer Protocol) to communicate
RestSharp in C#.
This is one of the several ways to create a web service or web request in .NET and comprehensive, open-source HTTP client library that works with all kinds of DotNet technologies.RestSharp is one of the best libraries that use requently REST to consume HTTP APIs in DotNet.THe RestSharp parsing automatically XML and JSON.Custom serialization and deserialization via ISerializer and IDeserializer and Both of synchronous and asynchronous requests.In the blog I am going to call api uing RestSharp in .NET Core.
Step 1
Create new project ThirdPartyAPIExample in .NET 5.
Installing Package for Entity framework core.
To install the package, just right click on the project ThirdPartyAPIExample and then select Manage NuGet package. The below dialog of the NuGet Package Manager will pop up.In the pop up browse tab,search the type of “RestSharp” in the search box and just click on the Install button.I am going to install lilke as
And install "Newtonsoft.Json" like as given above
Step 2.
I want to call third party api https://api.github.com/orgs/dotnet/repos so first create class.Right click on your Models folder and select Add >> New Item.An “Add New Item” dialog box will open. Select ASP.NET Core from the left panel, then select “Class” from templates panel and put the name as ThirdPartyAPIViewModel.cs.Press OK.
Open ThirdPartyAPIViewModel.cs file and put the following code into it.
public class ThirdPartyAPIViewModel
{
public int Id { get; set; }
public string Node_Id { get; set; }
public string Name { get; set; }
public string Full_Name { get; set; }
public string Private { get; set;}
public string Html_Url { get; set; }
public string Description { get; set; }
}
Step 3.
Right click on your Main project ThirdPartyAPIExample and select Add >> New Item.An “Add New Item” dialog box will open. Select ASP.NET Core from the left panel, then select “Class” from templates panel and put the name as WebApiRequestMethods.cs. Press OK.
Open WebApiRequestMethods.cs file and put the following code into it.
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace ThirdPartyAPICall
{
public interface IWebApiRequest<T, T1>
{
Task<T> GetAsync(T1 id, string authorizationHeader = "");
}
public class WebApiRequestMethods<T, T1> : IWebApiRequest<T, T1>
{
private string _uri;
public WebApiRequestMethods(string uri)
{
_uri = uri;
}
public async Task<T> GetAsync(T1 id, string authorizationHeader = "")
{
var client = new RestClient();
if (id != null && id.ToString().Trim() != "" && !id.ToString().StartsWith("/"))
{
client.BaseUrl = new Uri(_uri + "?" + id);
}
else if (id.ToString().Contains("/"))
{
client.BaseUrl = new Uri(_uri + id);
}
else
{
client.BaseUrl = new Uri(_uri);
}
var request = new RestRequest(Method.GET) { RequestFormat = DataFormat.Json };
if (!string.IsNullOrEmpty(authorizationHeader))
{
request.AddHeader("Authorization", authorizationHeader);
} var cancellationTokenSource = new CancellationTokenSource();
var response = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token);
if (response != null && (response.StatusCode == HttpStatusCode.OK) &&
(response.ResponseStatus == ResponseStatus.Completed))
{
try
{
return JsonConvert.DeserializeObject<T>(response.Content);
}
catch (Exception ex)
{
throw;
}
}
return default(T);
}
}
}
Step 4.
Right click on your Main Project ThirdPartyAPIExample and select Add >> New Item.An “Add New Item” dialog box will open. Select ASP.NET Core from the left panel, then select “Class” from templates panel and put the name as ServiceProvider.cs.Press OK.
using System.Collections.Generic;
using System.Threading.Tasks;
using ThirdPartyAPICall.Models;
namespace ThirdPartyAPICall
{
public interface IServiceProvider
{
Task<List<ThirdPartyAPIViewModel>> GetMethod(string url);
}
public class ServiceProvider : IServiceProvider
{
public async Task<List<ThirdPartyAPIViewModel>> GetMethod(string url)
{
WebApiRequestMethods<List<ThirdPartyAPIViewModel>, string> apiRequest
= new WebApiRequestMethods<List<ThirdPartyAPIViewModel>, string>(url);
var resp = await apiRequest.GetAsync("", "");
return resp;
}
}
}
Step 5.
Map dependencies in your Startup.cs.Open Startup.cs and put this code ConfigureServices function like as
//This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IServiceProvider, ServiceProvider>();//added code
services.AddControllersWithViews();
}
Step 6.
Open HomeController.cs file and put the following code into it.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace ThirdPartyAPICall.Controllers
{
public class HomeController : Controller
{
private readonly IServiceProvider _iServiceProvider;
public HomeController(ILogger<HomeController> logger, IServiceProvider iServiceProvider)
{
_iServiceProvider = iServiceProvider;
}
public async Task<IActionResult> Index()
{
var data =await _iServiceProvider.GetMethod("https://api.github.com/orgs/dotnet/repos");
return View();
}
}
}
Output
Comments