Skip to main content

The Other Side of the API

PHP scripts are not only servers — they call APIs too: fetching data, talking to services, integrating third parties. The built-in client is file_get_contents with a stream context: the URL alone makes a plain GET, the context adds methods, headers and a body. Three habits:

1. put ignore_errors in the context, so 4xx and 5xx responses still hand you their body,
2. check the status code — the first line of $http_response_header — before trusting the body,
3. json_decode the body and check for null before using the data.

(PHP also ships the cURL extension for advanced client work; everything here needs only the built-in streams.) The demos below call a local test server, so the outputs are stable — the client code is exactly what you would point at a real URL.


GET and Decode

The everyday task: GET a URL, check the status, decode the JSON body into arrays with json_decode($body, true) — from there it is ordinary PHP data.

Fetch a list into arrays

The response body decodes into a list of users, and from there it is ordinary PHP data — looped and printed field by field.

Prompt
Write a PHP script that GETs a JSON array of users from a server (a local built-in server in the demo), checks the status code from $http_response_header, decodes the body with json_decode, and prints each user's id and name.
Output: PHP script

POST with a JSON Body

Sending data is the mirror image: encode the array, put it in the context as content with the right Content-Type header, POST — then decode the server's answer, which here carries the id the server assigned.

Send an array, read the answer

The array goes out as JSON and the created record comes back with its new id — the complete write-path of an API client in one small program.

Prompt
Write a PHP script that encodes a new user to JSON and POSTs it through a stream context with the application/json content type to a server that assigns an id and answers 201 (a local built-in server in the demo), then decodes the response and prints the status and the created user with its new id.
Output: PHP script