Search code examples
node.jsrequestsquare-connect

Can't receive correct answer from Squareup API


I'm trying to send a post message to Square to create an item

var postData = {
        "name": "Milkshake",
        "variations": [
                        {
                            "name": "Small",
                            "pricing_type": "FIXED_PRICING",
                            "price_money": {
                                                "currency_code": "USD",
                                                "amount": 400
                                            }
                        }
                    ]}

request.post({
uri:"https://connect.squareup.com/v1/me/items",
headers:{'Authorization': 'Bearer ' + access_token,
             'Accept':        'application/json',
             'Content-Type':  'application/json'},
body: querystring.stringify(postData)
},function(err,res,body){
    console.log(res.statusCode);
    console.log(body); });

But I receive this message from Square

{"type":"bad_request","message":"invalid json"}

Solution

  • You're getting the error because you used querystring.stringify, which produces a URL encoded request body. You want JSON.stringify to produce a JSON encoded body. I.E:

    request.post({
    uri:"https://connect.squareup.com/v1/me/items",
    headers:{'Authorization': 'Bearer ' + access_token,
                 'Accept':        'application/json',
                 'Content-Type':  'application/json'},
    body: JSON.stringify(postData)
    },function(err,res,body){
        console.log(res.statusCode);
        console.log(body); });