Consume Web API with Auth0 using RestSharp in .NET 6
So, once again, I am back to consuming an API using RestSharp. I thought, hey, .NET 6 is new. It has this different way of building console apps. Might as well, build using that.
As always, the code is available here on GitHub.
The process of consuming an API is simple.
Step 1 — Find an API Server.
This is the most obvious step, or you wont be here. Unless, of course, you are a student, and you don’t have a API server of your own to practice against. If so, I would recommend, you use my own server.
More details about a ready to use server, is available at this link.
Random Stuff Generator
Welcome to the Random Stuff Generator. You know quotes. This project is a Content Management Solution (CMS). The…
As of this writing, the API server and the complementary web app client is available at the following links.
Step 2 — Pick a REST Library — RestSharp
It’s right there in the title. We are using RestSharp. Remember, you can consume APIs using the standard Web Client libraries provided by .NET 6.
RestSharp simply helps to make your life easy.
Step 3 — JSON to POCO Converting Utility — QuickType
Of course, you cannot use JSON directly in your project. Also, you should NOT try to code your own converters.
My recommendation. Use this website — https://quicktype.io/
Step 4 — Consuming the API.
Most of the time, you are concerned with two basic operations.
- GET call
- POST call
There are more things you do with an API server, but I am all about the essentials.
Here is how a GET looks.
- The function is async, Task based and uses a interface. This ensures that you are calling an await operation and you can map this with different response types. Makes your function reusable.
- Observe the part where I am adding an header. That is where I am putting the token. The spacing of the Bearer and the spelling of the Bearer is actually important.
- Observe, another part, where I am taking the JSON string and converting it to a C# Object, FromJson.
Here is how POST looks.
Here, the code is similar to the get. However, I will draw your attention to the part about, the POST body. That’s a JSON string.
That means, before the string arrives at this function, I have already created the POST body, converted it into a JSON string. That step, looks something like this.
I am sure RestSharp has lot more options, and I am only looking at GET and POST.
Still, this should get you started for the time being.