Making a POST request to an oAuth2 secured API using RestSharp

Recently, a coworker asked me how to best consume (using C#) an oAuth2 secured API which I had deployed.  I have been using RestSharp (along with JSON.NET) to make web requests in some of my applications recently, so I wrote a quick sample application for him demonstrating how to communicate with my API using those libraries.  I included it with the documentation for that API, but I want to share the basic concepts here as well.  Since the API is using oAuth2, the first step is to get an access token using an API key and password:

var url = "https://my.api.endpoint/GetToken";
var apiKey = "api_key";
var apiPassword = "api_password";

//create RestSharp client and POST request object
var client = new RestClient(url);
var request = new RestRequest(Method.POST);

//add GetToken() API method parameters
request.AddParameter("grant_type", "password");
request.AddParameter("username", apiKey);
request.AddParameter("password", apiPassword);

//make the API request and get the response
IRestResponse response = client.Execute(request);

//return an AccessToken
return JsonConvert.DeserializeObject(response.Content);

If you were successfully able to authenticate using your API credentials, you should receive a response that contains an access token and other information. Depending on the API you’re accessing, it may look similar to this:

"access_token": "v5s5UckbViR9gZUXiu...",
"token_type": "bearer",
"expires_in": 43199,
"userName": "api_key",
".issued": "Sun, 30 Jul 2017 17:05:37 GMT",
".expires": "Mon, 31 Jul 2017 05:05:37 GMT"

Now that the application has been authenticated and has been granted an access token, we can then provide this token when calling various API methods to get authorization.  Here is a sample POST request to my API, calling the DoStuff() method and including an object which contains the input parameters:

var url = "https://my.api.endpoint/DoStuff";

//create RestSharp client and POST request object
var client = new RestClient(url);
var request = new RestRequest(Method.POST);

//request headers
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", "application/json");

//object containing input parameter data for DoStuff() API method
var apiInput = new { name = "Matt", age= 34 };

//add parameters and token to request
request.AddParameter("application/json", JsonConvert.SerializeObject(apiInput), ParameterType.RequestBody);
request.AddParameter("Authorization", "Bearer " + access_token, ParameterType.HttpHeader);

//make the API request and get a response
IRestResponse response = client.Execute(request);

//ApiResponse is a class to model the data we want from the API response
ApiResponse apiResponse = new ApiResponse(JsonConvert.DeserializeObject(response.Content));

And that’s pretty much it – the ApiResponse object now has all the data we need from the server response, whatever that may be depending on the API.  As you can see, both of these libraries together make sending and receiving data to/from a server very easy with just a few lines of code.  Getting authenticated with the API server, sending some data, and receiving a deserialized response is very simple.  More information about RestSharp and JSON.NET can be found here:


10 thoughts on “Making a POST request to an oAuth2 secured API using RestSharp

    1. This is the access token required for oAuth2 authentication. When an API is secured with oAuth2, you first need to make a call to the authentication endpoint of that API. You provide a username and password, and the API returns an access token. You then provide this token when calling the various other API endpoints, as I am doing in my example. The token will typically expire after a set time, and you will need to reauthenticate and get a new token.


      1. Sergio – in my example, the AccessToken is a class I made myself, based on the data structure returned by the authentication endpoint for a given API. This may vary for each API. The Microsoft.AspNetCore.Authentication.Twitter and Microsoft.Owin.Security.Twitter namespaces are specific to authenticating with Twitter.


  1. Hello sir, I follow your code but now I am having this as a result. “{WWW-Authenticate=Bearer error=”invalid_token”}” i get a token then pass it to call a api but it returns StatusCode: Unauthorized.


  2. Hi,
    Great post.

    1) I have an header parameter for my POST request. How to add it?
    2) I don’t understand the following part of your code:
    //object containing input parameter data for DoStuff() API method
    var apiInput = new { name = “Matt”, age= 34 };
    Where did you get this object?

    Liked by 1 person

    1. For #1, you can any headers you want to your request with request.AddHeader(); For #2, that is just an anonymous object I created to match the parameters the API is expecting – a string for “name” and an int for “age”. This gets serialized to JSON with JsonConvert.SerializeObject(apiInput), and the API is expecting JSON in the body of the request.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s