Tristan Tran
Tristan Tran

Reputation: 31

How do I convert this cURL request to UrlFetchApp?

So the website gave us some code samples. I've managed to do GET functions well enough, but I can't seem to post anything. Here is the sample below

curl -X POST https://api.teachworks.com/v1/customers/family \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Token token={access_token}' \
  -d '{
        "customer": 
          {         
            "first_name": "Jake & Paula",       
            "last_name": "Jackson",
            "email": "[email protected]",
            "home_phone": "123-123-1234",
            "mobile_phone": "123-123-1234",
            "status": "Active"
           }
       }' 

Here is my code

function test(){
  url = "https://api.teachworks.com/v1/customers/family";
  var token = {api_key};
  headers = {
      "Accept": "application/json",
      "Authorization": "Token token="+token
    };
  payload = '{ "customer": \
{"first_name": "Jake & Paula", \
"last_name": "Jackson", \
"email": "[email protected]",\
"home_phone": "123-123-1234", \
"mobile_phone": "123-123-1234", \
"status": "Active" }}';
  Logger.log(payload);
  options = {
    "headers" : headers,
    "method" : "post",
    "payload" : payload
  }
  Logger.log(options);
  response = UrlFetchApp.fetch(url,options);
  Logger.log(response);
}

Every time I run it I get the same error:

Request failed for https://api.teachworks.com returned code 400. Truncated server response: Required parameter missing: customer

If I understand correctly, the payload is equivalent to -d. so my code should be right. Please let me know what i'm doing wrong.

Upvotes: 2

Views: 1006

Answers (1)

Tristan Tran
Tristan Tran

Reputation: 31

@theMaster was right about it missing the ContentType.

Accept in the headers is the receivable mimeType at the client side. contentType is for the option of UrlFetchApp and the same with Content-Type of the headers. Content-Type is the mimeType of request body. In your case, contentType of application/json is required to be used. Ref By the way, can I ask you whether you could confirm that your curl command worked fine? source comments @Tanaike

function test(){
  url = "https://api.teachworks.com/v1/customers/family";
  var token = {api_key};
  headers = {
      "Accept": "application/json",
      "Authorization": "Token token="+token
    };
  payload = '{ "customer": \
{"first_name": "Jake & Paula", \
"last_name": "Jackson", \
"email": "[email protected]",\
"home_phone": "123-123-1234", \
"mobile_phone": "123-123-1234", \
"status": "Active" }}';
  Logger.log(payload);
  options = {
    "headers" : headers,
    "method" : "post",
    "payload" : payload,
    "contentType": "application/json"
  }
  Logger.log(options);
  response = UrlFetchApp.fetch(url,options);
  Logger.log(response);
}

Upvotes: 1

Related Questions