Search code examples
phpjsonhttpful

JSON Array Syntax for PHP HTTP POST Requests


I'm attempting to write a PHP script that will query an API that I have access to. This API requires a JSON body post request, with one of the criteria being

"Analyses": ["Phenotype"]

Note that there are no double quotes around the second part of that string. When I try to pass this script below with Httpful, this script gives me an HTTP 500 result. Without the Analyses criteria, I get a proper response (albeit an error asking for the Analyses information) in a JSON format output. I assume this has something to do with the formatting/syntax of the Analyses string, and I'm not sure what to do about it. If I use single quotes, I get the 500 error. If I leave the quotes out entirely it assumes it's an array and give me an object error "Object reference not set to an instance of an object". I don't know how to pass that format without quotes around it.

$response = \Httpful\Request::post($url)
        ->sendsJson()
        ->body('{"apiUserKey":"abcde",
                "apiUserId":"efghi",
                "Species":"9606",
                "Analyses": "["Phenotype"]"
                 }')
        ->send();

Thanks!


Solution

  • You're example is almost right, but you are including one set of double quotes to many. You are trying to pass an array of strings in the "Analysis" field. The array itself does not need to be in double quotes.

    $response = \Httpful\Request::post($url)
        ->sendsJson()
        ->body('{"apiUserKey":"abcde",
                "apiUserId":"efghi",
                "Species":"9606",
                "Analyses": ["Phenotype"]
                 }')
        ->send();