Consuming Rest API in an Easy Way

Background There are numerous ways to consume REST API in C#. Starting with HttpClient, WebClient, HTTPWebRequest and Third-Party API. On this post, I will show you how to consume REST API in an easy way with C#. Requirements For this lab we use: Visual Studio 2019 – http://visualstudio.com Newton soft JSON - https://www.newtonsoft.com/json/ Rest sharp - http://restsharp.org/ Horoscope REST API sample – http://sandipbgt.com/theastrologer/api/horoscope // Let's get started #1 Creating a project with Visual Studio 2019 we created two projects the first one is Class Library and the second one is Console App. It used .NET Framework 4.7.2. we downloaded two Nuget package: Newtonsoft JSON and RestSharp for the Class Library project #2 Composing Classes for our REST objects The REST API will be consumed as an object. Therefore, we created several classes and enumeration #3 Creating Class that Consumes the REST API We created a class that has a method to consume REST API. We deserialize the REST API as shown below. We read the content and save the result into Zodiacresult Class. Please note we use DeserializeObject (from newtonsoft) and RestClient (from restsharp). #4 Creating Class that Display the REST API We created a console app that consume the library. The REST API has a nested result. Therefore, the Zodiacresult contains an array namely Meta object. We consume the Meta object and accessing through their properties. #5 Testing the result Lets push the F5 button and you can see, we can consume the rest API easily in dotnet. Have a question? Just put it in the comments. Enjoy your weekend. //

Topics Highlights

Translate It

About @ridife

This blog will be dedicated to integrate a knowledge between academic and industry need in Application Lifecycle Management (ALM), ICT tips, and Software Engineering Research. Enjoy this blog and let's get in touch in any social media.

Xbox

Month List