Page Content

Tutorials

REST API In PHP: HTTP Methods And Server Setup

The elements that one program uses to communicate with another, including classes, methods, functions, and variables, are defined by a program Programming Interface (API). An API’s purpose is to give other applications a way to transmit commands that will start a process inside the application and possibly produce some results. When a system is meant to be accessed outside by another program or library, or even internally within the same computer, you must provide an API. By linking a stock ticker to a Bloomberg API or a tweet stream to a Twitter API, for example, developers can communicate with an application through APIs.

One particular kind of API that uses HTTP as the communication protocol is called a REST API. Web applications use them extensively. Like regular websites, REST APIs work by having a client send an HTTP request and the server respond with an HTTP response.

One significant difference is that REST APIs heavily rely on HTTP status codes to show the outcome of a request. Since they normally do not feature a graphic user interface, the response body usually contains information in data formats such as JSON, XML, or any other document format instead of HTML with styling and scripts. Although they are not always user-friendly, REST APIs are meant to be HTTP-friendly.

Although there is a single, rigorous formal standard for REST APIs, developers often adhere to common guidelines that are supported by the HTTP standard. Every endpoint should communicate with a particular according to a well accepted principle. // is a proposed structure for API endpoints. A collection and the fundamental actions a client can take on them via the API are described by a RESTful web service.

HTTP Request Methods (Verbs)

HTTP specifies a collection of “verbs” or methods that specify the action that a request is attempting to take. Although there are eight methods, you will typically only use four of them:

To retrieve or information about them, use the GET function. Usually, a GET request is used to fetch data.

  • POST: Used to carry out an action or generate new POST request data can be supplied as JSON in the request body or in key-value format.
  • PUT: Used to replace a group of update a PUT with fresh information. It can serve as a “update” technique.
  • PATCH: A tool for applying partial PATCH updates. It can be used as a “update” method, just as PUT.
  • DELETE: This command eliminates or destroys data or DELETE.
    The Create, Retrieve, Update, and Delete (CRUD) activities that are common in databases are broadly represented by these methods (GET, POST, PUT, and DELETE). In order to simulate PUT and DELETE actions, some developers may decide to primarily use POST for writing data and GET for reading. The developer utilising the API can have a lot simpler and better experience by using the distinct verbs and routes depending on them.

API Development in PHP

PHP is a scripting language that works well for developing dynamic content and websites. It has built-in capabilities for managing requests and responses and is frequently utilised for web applications. One important use case for PHP is creating REST APIs.
PHP has extensions and functions for communicating with outside services. One tool for formatting and sending HTTP requests to access web services is the CURL extension.

Code Examples: REST Clients using CURL

Using CURL to retrieve data for a via a GET request is illustrated by the following code sample :

<?php
// Retrieving author data using CURL GET request
$authorID = "ktatroe";
$url = "http://example.com/api/authors/{$authorID}"; // The API endpoint
$ch = curl_init(); // Initialize a CURL session
curl_setopt($ch, CURLOPT_URL, $url); // Set the target URL for the request 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return the transfer as a string (implied from usage)
$response = curl_exec($ch); // Execute the request and get the response body 
$resultInfo = curl_getinfo($ch); // Get information about the transfer
curl_close($ch); // Close the CURL session
// Assuming the API returns JSON, decode the response 
$authorJSON = json_decode($response);
// Process the $authorJSON data
print_r($authorJSON); // Example: print the decoded JSON object/array
?>

A CURL session is started, the URL is set up, the GET request is sent, the server response is retrieved, and the response body assuming it is JSON is decoded by this script.
CURL is compatible with a number of HTTP protocols. A DELETE request utilising CURLOPT_CUSTOMREQUEST is demonstrated in the following example :

<?php
$authorId = 'ktatroe';
$bookId = 'ProgrammingPHP';
$url = "http://example.com/api/authors/{$authorId}/books/{$bookId}"; // Endpoint for the specific book 
$ch = curl_init(); // Initialize a CURL session 
curl_setopt($ch, CURLOPT_URL, $url); // Set the target URL 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); // Explicitly set the HTTP method to DELETE 
$result = curl_exec($ch); // Execute the request
$resultInfo = curl_getinfo($ch); // 
curl_close($ch); // Close the CURL session 
// Check $result and $resultInfo (like status code) for the outcome
print "DELETE request sent to $url. Result info:\n";
print_r($resultInfo); // Example: print information about the response
?>

This illustrates how to define methods like DELETE that are not supported by the default CURL options using CURLOPT_CUSTOMREQUEST. While updating may include using PUT or PATCH, which may also involve providing data in the body, creating usually requires the POST verb with data in the request body.

Building REST API Servers in PHP

Receiving HTTP requests, forwarding them, processing any supplied data (sometimes including database connections), and delivering a structured response usually in JSON format are all part of building a REST API server in PHP.

Reading the raw request body is frequently necessary for handling incoming requests, particularly when POST, PUT, or PATCH requests contain data in the body. Reading from php://input and then decoding the data for example, using json decode if the client sends JSON is how this is typically accomplished.

Based on the following excerpt shows how to read and decode the request body on the server side:

<?php
// Inside the server's request handling logic:
// Read the raw request body sent by the client
$requestBody = file_get_contents('php://input'); //
// Decode the JSON data from the request body into a PHP associative array
// The 'true' argument makes it return an associative array instead of objects 
$jsonData = json_decode($requestBody, true); // 
// $jsonData now holds the data sent by the client 
print_r($jsonData); // Example: print the decoded data received by the server
// The server would then use $jsonData to perform actions like database operations
?>

Following request processing, the server must send the response. Set the HTTP status code (200 for success, 201 for created, 404 for not found, and 500 for server error) and headers (e.g., Content-Type: application/json) before using json_encode to encode and transport response data

Use php -S localhost:8080 chap_07_simple_rest_server.php to start a basic PHP REST server on the command line with the built-in development server.

Skills and structure from PHP frameworks like Laravel, CodeIgniter, and Zend Framework simplify REST API development. Creating routes that map incoming HTTP methods and URLs to particular controller methods that manage the logic for each endpoint is a common task for these frameworks. Authentication and authorisation are important API security principles that require cautious handling. One standard for REST API security is OAuth 2.0.

REST API testing include sending queries to the different endpoints and confirming the replies, including the HTTP status codes and data type (such as JSON). There are tools available to help in testing, such as command-line tools like cURL or browser plugins. Since other people will probably use the API and need to know the arguments, endpoints, etc., documentation is also essential.

Index