0

I want to post the RESTful service from the name of the url is "https://api.pipedrive.com/v1/persons?api_token=tS5adsXC6V2nH991"
list of complete API is present in "https://developers.pipedrive.com/v1"

Following is my code

  string URL = "https://api.pipedrive.com/v1/persons?api_token=tS5adsXC6V2nH991";
            string DATA = @"{""object"":{""name"":""rohit sukhla""}}";
       var dataToSend = Encoding.UTF8.GetBytes(DATA);
                //Passyour service url to the create method
                var req =
                HttpWebRequest.Create(URL);
                req.ContentType = "application/json";
                req.ContentLength = dataToSend.Length;
                req.Method = "POST";
               req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
                var response1 = req.GetResponse();

I am getting the error

The remote server returned an error: (400) Bad Request.

please help

user1075564
  • 21
  • 2
  • 8
  • 2
    Maybe it has something to do with the `GetBytes("")` part? You're sending an empty request. Additionally there are easier ways to send HTTP requests than plain `WebRequest`. *Also* are you sure you wanted to publicly post that API key? If it was a secret you should invalidate and change it on the server end immediately. – Matti Virkkunen Apr 25 '16 at 09:26
  • This is not my actual api key this is dummy one. – user1075564 Apr 25 '16 at 09:33

2 Answers2

4

Here's my usual strategy for posting to external APIs, I hope it helps

using (var http = new HttpClient()) {
    // Define authorization headers here, if any
    // http.DefaultRequestHeaders.Add("Authorization", authorizationHeaderValue);

    var data = new ModelType {
        name = nameValue,
        email = emailValue
    };

    var content = new StringContent(JsonConvert.SerializeObject(data));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var request = http.PostAsync("[api url here]", content);

    var response = request.Result.Content.ReadAsStringAsync().Result;

    return JsonConvert.DeserializeObject<ResponseModelType>(response);
}

The request can also be awaited, instead of calling .Result directly.

To use this approach you need to create a c# model based on the response json structure. Oftentimes I use http://json2csharp.com/, provide a typical json response from the endpoint I'm interested in, and the c# model gets generated for me automatically.

DrinkBird
  • 834
  • 8
  • 17
0

The wrapper object with a key called "object" looks extraneous to me. You should probably post just the inner object.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159