Sending a JSON POST request to REST API in PHP

php api call json
php get json data from api
post api in php
php post json
php post request
how to fetch data from api in php
how to get curl post data in php
php curl get request with headers

I need to make a POST request using a JSON object as the body. Both of these methods are giving me HTTP 500 server errors. Is there anything glaringly wrong with my code? Be gentle... I've tried several methods including

$checkfor = ("'serverId':'Server','featureId':'Feature','propertyId':'Property'");
    $checkforJson = json_encode($checkfor);
    $uri = "http://localhost:8080/v1/properties";
    $response = \Httpful\Request::post($uri)

Which uses the HTTPful resource. And I have tried using cURL

$service_url = "http://localhost:8080/v1/properties";

   // Initialize the cURL
   $ch = curl_init($service_url);

   // Set service authentication

   // Composing the HTTP headers     
   $body = array();
   $body[] = '"serverId" : "Server"';
   $body[] = '"featureId" : "Feature"';
   $body[] = '"propertyId" : "Property"';
   $body = json_encode($body);

   $headers = array();
   $headers[] = 'Accept: application/xml';
   $headers[] = 'Content-Type: application/xml; charset=UTF-8';

   // Set the cURL options
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
   curl_setopt($ch, CURLOPT_POST, TRUE);
   curl_setopt($ch, CURLOPT_VERBOSE, 1);
   curl_setopt($ch, CURLOPT_HEADER, TRUE);
   curl_setopt($ch, CURLINFO_HEADER_OUT, true);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

   curl_setopt($ch, CURLOPT_TIMEOUT, 15);

   // Execute the cURL
   $data = curl_exec($ch);

   // Print the result

Your json_encode requires an array.

It should look like this


$checkfor = ([

$checkforJson = json_encode($checkfor);
var_dump($checkforJson); // this will now work

For better understanding read doc

UPDATE I also notice on the curl script, your array needs fixed again

 $body['serverId'] = 'Server';

and dont json encode the post fields afterwards, it takes an array.

Sending a JSON POST request to REST API in PHP, How do I send a post request to Rest API? But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and reads it into a string. Later, we can use the json_decode() function to decode the JSON string.

I had similar issues a while back.

A solution that worked for me was this:

$url = '';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($data),

$context  = stream_context_create($options);
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

Similar answers can be found HERE

How do I send a POST request with PHP?, $fields_string = http_build_query($fields); //open connection $ch = curl_init(); // Then connect to with Postman and send http requests. Note: when making PUT and POST requests, make sure to set the Body type to raw, then paste the payload in JSON format and set the content type to JSON (application/json). Secure Your PHP REST API with OAuth 2.0

Have you tried:

$body = array(
  "serverId" => "Server",
  "featureId" => "Feature",
  "propertyId" => "Property",

$body = json_encode($body);

Maybe its the way your array is setup

Sending JSON via POST in PHP, <?php //API Url $url = ''; //Initiate cURL. $ch = curl_init($url); //The JSON data. $jsonData = array( 'username'  When you working with web services and APIs, sending JSON data via POST request is the most required functionality. PHP cURL makes it easy to POST JSON data to URL. In this tutorial, we will show you how to POST JSON data using PHP cURL and get JSON data in PHP.

cURL API calls with PHP and json data (GET - POST - PUT, REST API calls with cURL, PHP and json so for a GET we can just set $data on false, because we are not passing any data with a GET call. M Series,T Series,PTX Series,MX Series. Use an HTTP POST request to send single or multiple RPC requests to the REST API. You can use the POST request to do device configuration.

PHP-Send HTTP Get/Post Request and Read JSON response , PHP-Send HTTP Get/Post Request and Read JSON response Download the source code Duration: 22:04 Posted: Jun 18, 2019 I need to send a JSON (which I can stringify) to the server and to retrieve the resulting JSON on the user side, without using JQuery. If I should use a GET, how do I pass the JSON as a parameter?

How to receive JSON POST with PHP, Get and Post method using Fetch API · HTTP GET and POST Methods in PHP · Difference Between JSON and AJAX · Python | Sort JSON by value · How to create  How to Send HTTP Request and Parse JSON Data Using Java - Duration: 27:22. Coding Master - Programming Tutorials 21,395 views

  • great. 500 errors usually tell you exactly where your code went wrong. what does your error_log say?
  • PHP warning, json_encode() expects parameter 2 to be integer from the Apache logs. And the server itself is erroring with status.code unknown (helpful i know)
  • Unforunately, this didn't work for me. But i will make sure to keep it in my code, thank you for the tip
  • you must have more errors then, but this at least gets you the correct array. any new error messages?
  • Yeah I am now getting the json_decode() expects parameter 1 to be string, resource given in /var/www/etc
  • Aha! Following your updates i have stopped getting any errors in Apache! I am getting a server error saying "status.cause:com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input" - but i assume that is another question for another thread? Edit: I was decoding in the first example, not the second, apologies.
  • Yeah i had a hunch that was the case. I did look up code 100 and saw it's nothing bad. I will continue looking into the Java errors.
  • Sorry man I'm kind of a n00b at coding, I am getting an output from that of resource #id 3. How do i view the contents of Context?
  • You can use $result = file_get_contents( $url, false, $context ); $response = json_decode( $result ); after $context and access it via the $response
  • That appears to have worked Daryn. However i believe there is an issue with the format in which the Json is being parsed. Which is an error being thrown by a Java server so i am going to look more into that. Thank you for your help man
  • Unfortunately, neither of these worked. Thank you for the suggestion though