How to consume a web api with C#โ“

How to consume a web api with C#โ“

This is a repost of my article published on my blog: Unit Coding go and check it out! โœจ

In nowadays itโ€™s hard to think about an application that cannot benefit from data, being this itโ€™s own data or data from a third party source and that is exactly what web apis do for our applications they enrich us with data they provide and we can use it to create some advanced services or to display pretty useful information and in logical ways to serve for a specific purpose. For this reason I will show you how you can get that benefit from web apis using C# and .NET 7 so you can take advantage of this essential building blocks for modern software development.

First we need an API to call ๐Ÿ“ž

First of all we will use the Json Placeholder API this is a pretty useful web api to generate and get fake data quite fast and thatโ€™s exactly what we need for this simple call no need to pay or register to use, just plug and play.

I donโ€™t want to get too much into detail with the API I will just tell you that you should bookmark it as itโ€™s super useful for simple projects and you can read the documentation they provide itโ€™s pretty straight forward.

How to use the API ๐Ÿ‘จ๐Ÿฝโ€๐Ÿซ

The way we will be calling the api is to call fake blog posts but you can also get comments for that blog, albums, photos, etc. Make a call to the api in the browser like this [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts) and you should see the data like the one below.

but we are getting way too many blogs we just need one to display in our app for this demonstration purposes so a way of getting just one is to make the call this other way [https://jsonplaceholder.typicode.com/posts/1](https://jsonplaceholder.typicode.com/posts/1) . Here we are telling the api to get us the blog with the id equals to 1 and as we expected we are only getting that blog specifically.

Create a new .NET console app ๐Ÿ’ป

I know you are getting impatient to call this into your app so now create a new console application. I will use visual studio code but you can use Visual Studio if you want, also Iโ€™m using the version 7 of .NET you can use any version of .net core that you want just be aware that the program.cs file may vary from version to version as in .NET 7 there is no Main function.

I will create the console app using the dotnet cli command shown below

dotnet new console -o [YourProjectName]

Now into the program.cs letโ€™s create an instance of the HttpClient class and type the following code

HttpClient client = new()
{
    BaseAddress = new Uri("https://jsonplaceholder.typicode.com/")
};

var response = await client.GetAsync("posts/1");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);

As I said we are creating an instance of the HttpClient and inside the constructor we are assigning a value to the BaseAddress propertie, here you will paste the web api address as shown in the code. Then we are making the call with the client to get only one post. From there we get the content from the call and read it as a string to finally print it to the console, so you should see an output like the following in your console.

{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Now we are getting the actual data from the api, but this data can not be easily manipulated this way, we still need to parse this JSON data into an object so we can manipulate it for our purposes.

Parsing JSON to C# Object ๐Ÿ•น๏ธ

To parse JSON data into a C# object we need to create a class that mimics the structure of the JSON response, for this we need a Post class that contains values for userId, postId, title and body, so the class would end looking like this.

public class Post
{
    [JsonProperty("userId")]
    public int UserId { get; set; }
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("body")]
    public string Body { get; set; }

    public override string ToString()
    {
    return $"Post Id:{this.id} \n UserId:{this.userId} \n Title: {this.title} \n Body: {this.body}";
    }
}

We are using the JsonProperty to let C# now that we want to map our post properties using PascalCasing to the json response properties using camel casing, other way to map them would be using camel casing in out class like public int userId {get; set;} and we would not need to use the JsonProperty. Also you can note that below in the class I overrode the ToString() function to display the Blog data in a more structured way.

So now back to the Program.cs file we need a way to convert(Serialize) the JSON response to a C# object, above the call to print the blog to the console we should nowdsfdsfdsf add a call to the JsonSerialiezer class to deserialize our JSON response into our new Post class and we should now change what we are printing to the console.

var post = JsonSerializer.Deserialize<Post>(content);
Console.WriteLine(post.ToString());

After running again the project with this last changes the output should be as following:

Post Id:1
UserId:1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body: quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto

Now that we are parsing the json data to an actual c# class we can manipulate the data to our convenience and this in a greater scale can led you to build amazing, complex and very usefull appplications.

Conclusion ๐Ÿ“

This will be it, now you now the basics to call and consume a web api and how to manipulate the data to make it have more sense and provide more value all of this using C#. I hope you can use this new knowledge to create something amazing that will make your programming skills grow, as there is no better way of mastering any knowledge than building something that can be used by average people.

If you desire to go one step ahead and create a cool application using a web api and C# you can check out my past blog about building a pokedex using the pokemon api and blazor to display the first 150 pokemon and display their data, aslo if you enjoyed this reading please provide any feedback on anything that I can do to get at writting as english is not my main language but I love writting and helping people to learn while making some fun things on the way.

Support me on my social media ๐Ÿ‘๐Ÿฝ

If you want to keep reading or listening about me show some love ๐Ÿ’– to this blog and also you can support my youtube ๐Ÿ“ฝ๏ธ channel with your subscription and also you can subscribe to my Kofi โ˜• to get the source code from my coding projects on youtube. Iโ€™m hoping to build a beautiful community to give you all guys all the knowledge that I would have love to be available when I was starting to learn to code. Thanks for your time and I hope to see you on my next article, see you!!!

Did you find this article valuable?

Support Oscar Montenegro ๐Ÿง™๐Ÿพโ€โ™‚๏ธ๐ŸŒŸ by becoming a sponsor. Any amount is appreciated!

ย