Consume Rest API in C #


I would like you to guide me a bit with this. I am trying to consume an API Rest in C # and have an authentication where I must pass these parameters or values: username , password , client_id , client_secret , grant_type , scope but I do not know how to pass those values.

I'm doing something like this:

HttpWebRequest request = WebRequest.Create("MiDireccionAPI") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; //"application/json; charset=utf-8";
request.Headers.Add("username", "miUsuario");
request.Headers.Add("password", "MiClave");
request.Headers.Add("grant_type", "Migrant_type");
request.Headers.Add("client_id", "Miclient_id");

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string resp = reader.ReadToEnd();

And it's supposed that he should return a token like this and a code 200 :


But I get error 400 because I imagine that the past of the parameters is wrong.

If someone clarifies to me how to pass this type of values to an API, since I am a beginner in this and I did not find something that really serves me.


I have a website made in that makes invoices and I must consume this API and which uses OAuth 2.0, this API is from a government entity in my country that is responsible for receiving invoices for this API but this API a token must be generated to be able to send what is occupied.

What I'm trying to do is generate that token to send the invoices.

This website is published on a server.

asked by Alex 03.04.2017 в 17:23

2 answers


Explore the api you want to connect to using a tool like Postman , with it you can similar the Request in different ways until you discover what are the exact parameters you need, what kind of request (GET, POST, ETC) and where to place them (header, body, etc).

Already with that information it is easy to create a client.

Seeing your example, modify it in the following way:

HttpWebRequest request = WebRequest.Create("MiDireccionAPI") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; 

// Metodo modificado
string postData = "username=miUsuraio&password=MiClave&grant_type=password&client_id=Miclient_id";    byte[] byteArray = Encoding.UTF8.GetBytes (postData);  
request.ContentLength = byteArray.Length;  
using (Stream dataStream = request.GetRequestStream (){
    using (StreamWriter stmw = new StreamWriter(dataStream))
    dataStream.Write (byteArray, 0, byteArray.Length);  

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    string resp = reader.ReadToEnd();

The grant_type was modified, when you are authenticating, the grant_type = password is sent to request the token.

Another point to consider is that if the server you are connecting to was made with Web API 2 try to find a url of the type:


Since authentication by default is set to / Token


Change the example to use POST instead of Headers.

answered by 03.04.2017 в 18:37

You can try to implement it in this way, which is what I always use and it works for me.

first you will need the Newtonsoft.Json to de-serialize the answer and so in case you get errors you can know what the error was. You install it from the NuGet package manager

Now to implement the call to the api you will also need to add references to


and with this you can already use this code, substituting the values that you need to send in the headers and the object that has to be sent.

        //declare api client 
        static HttpClient client = new HttpClient();
        //Initialize api client
        if (client.BaseAddress == null)
            client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings.Get("WS_URL"));
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //Add headers
        client.DefaultRequestHeaders.Add("X_PUBLIC_KEY", PublicKey.ToString());
        client.DefaultRequestHeaders.Add("X_TIME", date);
        client.DefaultRequestHeaders.Add("X_TOKEN", CreateToken(PrivateKey + date, PrivateKey));

        //Call client.PostAsJsonAsync to send a POST request to the appropriate URI   
        HttpResponseMessage resp = client.PostAsJsonAsync("api/Vehiculo/Add", object).Result;
        //This method throws an exception if the HTTP response status is an error code.  
        //var xx = resp.EnsureSuccessStatusCode();
        if (resp.IsSuccessStatusCode)
            var resultado = resp.Content.ReadAsAsync<Vehiculo>().Result;
            return resultado;
            var resultado = resp.Content.ReadAsStringAsync().Result;
            var result = JsonConvert.DeserializeObject<ResultServer>(resultado);
            throw new Exception(string.Format("Message:{0}, ExceptionMessage: {1}", result.Message, result.ExceptionMessage));
    catch (Exception ex)
        throw new Exception(string.Format("AddVehicle - Error: {0}", ex.Message));

I hope this code will help you, and I'll keep everything up to date.

Update ...

From what I see in the image of your postman, the data you send in the call is not a header, but an object with the parameters username, password, etc ...

then the problem is that in your code you are adding those values as headers. What you have to do is create a class that contains those parameters with the same name as you are sending them, and instantiate it by assigning values, to send it in your call to the api, which in the example code that you attach before is done in this line:

//Call client.PostAsJsonAsync to send a POST request to the appropriate URI   
        HttpResponseMessage resp = client.PostAsJsonAsync("api/Vehiculo/Add", object).Result;

Being object, the instance to your created class.

I hope I have been of help, I stay tuned

answered by 07.04.2017 в 22:54