Post JSON data to REST API

How do you post JSON data using PHP cURL? Sometimes, the API you are working with will require that you send JSON data. But your initial data is not JSON. How do you convert your data to JSON as the API server had requested?

Your initial data could be an array or HTML form data. However the situation, you can always cast your data from one type to another. In this tutorial, you would learn how to send JSON data via cURL.

To send JSON to a REST API endpoint, you should send an HTTP POST solicitation to the REST API server and give JSON information in the body of the POST message. You additionally need to determine the information type in the body of the POST message utilizing the Content-Type: application/json demand header

cURL is a PHP library and command-line tool that allows you to send and receive files over HTTP and FTP. You can use proxies, pass data over SSL connections, set cookies, and even get files that are protected by a login.

To make a POST request to an API endpoint, you need to send an HTTP POST request to the server and specify a Content-Type request header that specifies the data media type in the body of the POST request. The Content-Length header indicates the size of the data in the body of the POST request. In this case, the content type is:

'Content-Type: application/json',
'Content-Length: ' . strlen($payload))

By the time you are done studying this tutorial, you would have learned how to post JSON data using PHP cURL.

This tutorial assumes you are fairly good with PHP. You already know to consume API with PHP cURL to a certain degress.

Let’s assume you have your payload as follows:

$payload = '{
	"shipment": [{
		"items": [{
			"category": "Electronics",
			"description": "iPhone",
			"weight": 20,
			"quantity": 1,
			"value": 100
		}],
		"itemCollectionMode": "DropOff",
		"pricingTier": "Standard",
		"insuranceType": "None",
		"insuranceCharge": 0,
		"discount": 0,
		"shipmentRoute": "Domestic",
		"shipmentCharge": 1,
		"pickupCharge": 0,
		"senderDetail": {
			"name": "Whizdom",
			"email": "[email protected]",
			"phoneNumber": "0123456789",
			"addressLine1": "123 Main St",
			"addressLine2": "123 Main St",
			"addressLine3": "",
			"country": "Nigeria",
			"state": "Lagos",
			"city": "Ojota",
			"countryCode": "NG",
			"postalCode": "300001"
		},
		"receiverDetail": {
			"name": "Alice Smith",
			"email": "[email protected]",
			"phoneNumber": "0123456789",
			"addressLine1": "123 Main St",
			"addressLine2": "123 Main St",
			"addressLine3": "",
			"country": "Nigeria",
			"state": "Edo",
			"city": "Benin",
			"countryCode": "NG",
			"postalCode": "300001"
		}
	}]
}';
<?php 
// Initialise a new cURL session
$ch = curl_init('https://mytopship-staging.herokuapp.com/api/save-shipment');

// Return the result of POST request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get information about the last transfer
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

// Use POST request
curl_setopt($ch, CURLOPT_POST, true);

// Set payload for POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 
// Set HTTP Header for POST request 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);
 
// Execute a cURL session
$result = curl_exec($ch);
 
// Close cURL session
curl_close($ch);
//print out the result
print_r($result);
?>

I hope you’d find this tip useful in your code. Happy coding.

Image by Ben Griffiths

Leave a Reply

Your email address will not be published. Required fields are marked *