1

I'm trying to submit a POST request with JSON data to an api endpoint. The endpoint requires a querystring passing the api credentials, but also requires the JSON data to be POSTed.

When I try to do this with PHP cURL as shown below, the querystring is apparently removed - thus the api is rejecting the request due to missing api key.

I can do this easily with Postman when testing access to the api endpoint.

How can I make the cURL request include both the querystring AND the JSON POST body?

Example code:

// $data is previously defined as an array of parameters and values.

$url = "https://api.endpoint.url?api_key=1234567890";

$ch = curl_init();
$json = json_encode($data);

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json)
] 

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

1 Answer 1

1

You are doing almost right.

Sometimes you need to relax SSL verification.
Otherwise, update php ca bundle:
https://docs.bolt.cm/3.7/howto/curl-ca-certificates

Add the following:

$headers = array(
  "Content-type: application/json;charset=UTF-8",
  "Accept-Encoding: gzip,deflate",
  "Content-length: ".strlen($json),
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "identity, deflate, gzip");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

Sometimes you need to change encoding too:

$result = utf8_decode($result);

And check the returning data.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that fixed it! Who would have guessed it was a HTTPS certificate issue, not an encoding or header issue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.