JSON Post Requests

APIs are fantastic and it’s no secret that developers love them. In short, APIs are a set of rules that allow for two different software components to communicate with one another in an automated way. In this article I will look at how to use PHPs file_get_contents to send a JSON POST request to a RESTful endpoint.

First, you will need to declare an array in PHP. This will be storing the data you will be sending to the RESTful web service endpoint. We will use json_encode to turn the PHP array into a JSON object. How you build this array and will mostly depend on how the RESTful web service is built. The API should have documentation explaining what the JSON object needs to look like and from there you can decode it back to a PHP array. There are a lot of websites online that do exactly this for you, one of my favorites is Free Online Tools 24.

Now we are ready to use file_get_contents to POST this JSON object to a specific RESTful endpoint or url. Take note of the content-type header as this is what will tell the API to read your POST as JSON. The content is set to the PHP variable which is just the PHP array we encoded into JSON above.

That’s it! Now we are ready to start exchanging data with any HTTP RESTful web service.

Leave a Reply