How to Create RESTful API in PHP

AuthorSumit Dey Sarkar

Pubish Date13 Apr 2023

categoryPHP

In this tutorial we will learn how to create reate RESTful API in PHP.

 

How to Create RESTful API in PHP

Creating a RESTful API in PHP involves the following steps:

 

Step 1 - The HTTP methods and API endpoints should be defined: Select the HTTP methods that will be used to communicate with the API's public endpoints (such as GET, POST, PATCH PUT, and DELETE).

 

Step 2 - Set up the server environment: You will need a server to run the PHP code. You can either deploy your code to a production server or use a local development environment like XAMPP or WAMP.

 

Step 3 - Create PHP files for each endpoint: For each endpoint, create a PHP file that will handle requests and responses. Then an endpoint delivers a list of users, the file should be titled after that endpoint, such as "users.php".

 

Step 4 - Implement the API logic: In each PHP file, implement the logic that will handle the request and generate a response. This may entail running database queries, handling input data, and producing output in the desired format (for example, JSON or XML).

 

Step 5 - Handle errors and exceptions: Handle any errors or exceptions that may occur during API calls and return appropriate error responses with meaningful error messages.

 

Step 6 - Test the API: Test the API endpoints using a tool like Postman or a simple web form to ensure that they are working as expected.

 

Here's an example of a simple RESTful API in PHP that returns a list of users:

 

GET /users: Create a new user.

// users.php

// Set the content type to JSON
header('Content-Type: application/json');

// Define the list of users
$users = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Jane'),
    array('id' => 3, 'name' => 'Bob'),
);

// Handle GET requests to /users
if ($_SERVER['REQUEST_METHOD'] == 'GET' && strpos($_SERVER['REQUEST_URI'], '/users') === 0) {
    // Return the list of users
    echo json_encode($users);
} else {
    // Return a 404 error
    http_response_code(404);
    echo json_encode(array('error' => 'Endpoint not found'));
}

 

POST /users: Create a new user.

// users.php

if ($_SERVER['REQUEST_METHOD'] == 'POST' && strpos($_SERVER['REQUEST_URI'], '/users') === 0) {
    // Get the user data from the request body
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate the user data
    if (!isset($data['name']) || !isset($data['email'])) {
        http_response_code(400);
        echo json_encode(array('error' => 'Invalid user data'));
        exit;
    }
    
    // Save the user to the database
    // ...
    
    // Return the new user ID
    http_response_code(201);
    echo json_encode(array('id' => $newUserId));
} else {
    http_response_code(404);
    echo json_encode(array('error' => 'Endpoint not found'));
}

 

PUT /users/{id}: Update an existing user.

// users.php

if ($_SERVER['REQUEST_METHOD'] == 'PUT' && preg_match('/^\/users\/(\d+)$/', $_SERVER['REQUEST_URI'], $matches)) {
    // Get the user ID from the URL
    $userId = $matches[1];
    
    // Get the user data from the request body
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate the user data
    if (!isset($data['name']) || !isset($data['email'])) {
        http_response_code(400);
        echo json_encode(array('error' => 'Invalid user data'));
        exit;
    }
    
    // Update the user in the database
    // ...
    
    // Return a success message
    http_response_code(200);
    echo json_encode(array('message' => 'User updated successfully'));
} else {
    http_response_code(404);
    echo json_encode(array('error' => 'Endpoint not found'));
}

 

PATCH /users/{id}: Partially update an existing user.

// users.php

if ($_SERVER['REQUEST_METHOD'] == 'PATCH' && preg_match('/^\/users\/(\d+)$/', $_SERVER['REQUEST_URI'], $matches)) {
    // Get the user ID from the URL
    $userId = $matches[1];
    
    // Get the user data from the request body
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Update the user in the database
    // ...
    
    // Return a success message
    http_response_code(200);
    echo json_encode(array('message' => 'User updated successfully'));
} else {
    http_response_code(404);
    echo json_encode(array('error' => 'Endpoint not found'));
}

 

DELETE /users/{id}: Delete an existing user.

// users.php

if ($_SERVER['REQUEST_METHOD'] == 'DELETE' && preg_match('/^\/users\/(\d+)$/', $_SERVER['REQUEST_URI'], $matches)) {
    // Get the user ID from the URL
    $userId = $matches[1];
    
    // Delete the user from the database
    // ...
    
    // Return a success message
    http_response_code(200);
    echo json_encode(array('message' => 'User deleted successfully'));
} else {
    http_response_code(404);
    echo json_encode(array('error' => 'Endpoint not found'));
}

Some examples of how you can implement different HTTP methods in a PHP RESTful API.

Comments 0

Leave a comment