Most of the APIs are used to accept requests and send responses in JSON format. JSON is the de-facto data exchange format. It is important to learn how to send JSON request data with an API call.
The cURL is a way of remote accessing the API endpoint over the network. The below code will save you time to achieve posting JSON data via PHP cURL.
It prepares the JSON from an input array and bundles it to the PHP cURL post.
It uses PHP json_encode function to get the encoded request parameters. Then, it uses the CURLOPT_POSTFIELDS option to bundle the JSON data to be posted.
<?php // URL of the API that is to be invoked and data POSTed $url = 'https://example.com/api-to-post'; // request data that is going to be sent as POST to API $data = array( "animal" => "Lion", "type" => "Wild", "name" => "Simba", "zoo" => array( "address1" => "5333 Zoo", "city" => "Los Angeles", "state" => "CA", "country" => "USA", "zipcode" => "90027" ) ); // encoding the request data as JSON which will be sent in POST $encodedData = json_encode($data); // initiate curl with the url to send request $curl = curl_init($url); // return CURL response curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Send request data using POST method curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); // Data conent-type is sent as JSON curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type:application/json' )); curl_setopt($curl, CURLOPT_POST, true); // Curl POST the JSON data to send the request curl_setopt($curl, CURLOPT_POSTFIELDS, $encodedData); // execute the curl POST request and send data $result = curl_exec($curl); curl_close($curl); // if required print the curl response print $result; ?>
The above code is one part of the API request-response cycle. If the endpoint belongs to some third-party API, this code is enough to complete this example.
But, if the API is in the intra-system (custom API created for the application itself), then, the posted data has to be handled.
This is to handle the JSON data posted via PHP cURL in the API endpoint.
It used json_decode to convert the JSON string posted into a JSON object. In this program, it sets “true” to convert the request data into an array.
<?php // use the following code snippet to receive // JSON POST data // json_decode converts the JSON string to JSON object $data = json_decode(file_get_contents('php://input'), true); print_r($data); echo $data; ?>
The json_encode function also allows setting the allowed nesting limit of the input JSON. The default limit is 512.
If the posted JSON data is exceeding the nesting limit, then the API endpoint will be failed to get the post data.
In a previous tutorial, we have seen many examples of sending requests with PHP cURL POST.
This program sets the content type “application/json” in the CURLOPT_HTTPHEADER. There are other modes of posting data via PHP cURL.
Note: PHP http_build_query() can output the URL encoded string of an array.