HTTP methods
Learn the GET, POST, PUT and DELETE HTTP methods and their REST use.
HTTP methods and their jobs
REST APIs use four main HTTP methods: GET reads a resource, POST creates a new resource, PUT updates an existing one, DELETE removes a resource. Each method has one clear job.
The request method is read from $_SERVER['REQUEST_METHOD']. To fetch data from an external API, PHP's file_get_contents function can send a request to a URL and return the response as a string. The returned string is then decoded into an array.
External requests with file_get_contents
To fetch data from an API, you pass a URL to file_get_contents. The function sends a request to the URL and returns the response as a string. If the returned string is in a structured data format, you decode it into an array and access its fields.
You can also read a local file with the same function by passing a file path instead of a URL. This lets you write sample data to a file and read it back to safely try the request flow.
Exercise Read from a file and convert to an array
The $file variable holds a file path with sample data already written to it. Read the file with file_get_contents and assign it to $content. Then decode $content into an array (with true) and assign it to $data. Finally, print the value of $data['name'].
Show example solution
Read $file with file_get_contents, decode $content into an array, print name with echo.
Example solution:
$content = file_get_contents($file);
$data = decode($content, true);
echo $data['name'];
Test yourself
-
Which HTTP method creates a new resource?
- GET
- DELETE
- POST
- PUT
Show answer
POST — Correct. The POST method is used to create a new resource.
-
Match HTTP methods with their jobs
- GET
- reads a resource
- POST
- creates a new resource
- PUT
- updates a resource
- DELETE
- removes a resource
-
Read a string from a file
$file = sys_get_temp_dir() . '/api_data.txt'; file_put_contents($file, '{"name":"Alex"}'); $content = ____($file); $data = decode($content, true);Show answer
$file = sys_get_temp_dir() . '/api_data.txt'; file_put_contents($file, '{"name":"Alex"}'); $content = file_get_contents($file); $data = decode($content, true);