Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API PATCH request

Tags:

rest

c#

mailchimp

I'm trying to send requests and get responses from MailChimp API . . so far, GET, POST and DELETE are working good however, PATCH always results to Bad Request can you identify the error in this code?

string data = "{\"name\": \"TestListTWOTWOTWO\"}";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Headers[HttpRequestHeader.Authorization] = accessToken;
request.Method = "PATCH";
request.ContentType = "text/plain;charset=utf-8";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        // Send the data.
        requestStream.Write(bytes, 0, bytes.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

the error occus on the line with request.GetResponse(); it is an unhandled WebException saying The remote server returned an error: (400) Bad Request

after checking the error response, here's the what it says

"Your request doesn't appear to be valid JSON:

\nParse error on line 1:\nPATCH /3.0/lists/9bb\n^\n
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['"
like image 450
Jan Lyndon Jasa Avatar asked Jun 25 '15 06:06

Jan Lyndon Jasa


1 Answers

Many C# libraries seem to try to use the Expect: 100-Continue header, which MailChimp/Akamai has a problem with when combined with PATCH. You have two options.

  1. Turn off Expect: 100-Continue in your HTTP library. In one C# library, you do that with a line of code like Client.DefaultRequestHeaders.ExpectContinue = False

  2. Tunnel the PATCH request through HTTP POST using the X-Http-Method-Override header. Here's more details on that header.

like image 181
TooMuchPete Avatar answered Nov 13 '22 12:11

TooMuchPete