DEV Community

Oscar Montenegro
Oscar Montenegro

Posted on • Updated on • Originally published at unitcoding.com

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! ✨

How to consume a web api with C# ❓

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.

Json Placeholder web api wehpage

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 and you should see the data like the one below.

Json response for all blogs

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 . 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.

Json response for one blog

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]
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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 purposses.

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}";
        }
}
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 🙋🏽‍♂️!!!

Good bye chat gif

Subscribe to youtube image

Support me on lo fi image

Top comments (0)