Building A Rest API With PHP

It’s been a long time since I haven’t written an article but nowadays I’m very much focused on learning new things and upgrading myself. Meantime I got the idea to write about Rest Api so that fellow learners can learn if they don’t know.

Before start building a rest API I would love to explain a few first things that would help you to get a deeper knowledge of what exactly it is.

What is a Rest API

A REST API (Representational State Transfer Application Programming Interface) is a type of API that is used to interact with web services or web applications. It has a set of rules that allows requests to communicate over the internet. In simple words, the Rest API is a way for software to talk to each other.

For example, You have created an application to handle the products or you have a table of products. Now you want to show the products and delete them or you want to perform any action then you can run the Rest API request to the backend using the Javascript fetch() method.

fetch('/products', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'New Product',
    description: 'This is a new product',
    price: 9.99
  })
})
  .then(response => {
    // Handle the response, which will be a 201 Created status code if the product was created successfully
  })
  .catch(error => {
    // Handle errors
  });

and in backend, you could do like this.

<?php

require_once('config.php'); //e.g database connection

// Define endpoint to get all products
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['REQUEST_URI'] == '/products') {
    $query = "SELECT * FROM products";
    $result = mysqli_query($connection, $query);
    $products = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $products[] = $row;
    }
    
    header('Content-Type: application/json');
    echo json_encode($products);
}

// Define endpoint to get a single product by ID
if ($_SERVER['REQUEST_METHOD'] == 'GET' && preg_match('/\/products\/(\d+)/', $_SERVER['REQUEST_URI'], $matches)) {
    $id = $matches[1];
    $query = "SELECT * FROM products WHERE id = $id";
    $result = mysqli_query($connection, $query);
    $product = mysqli_fetch_assoc($result);
    
    if ($product) {
        header('Content-Type: application/json');
        echo json_encode($product);
    } else {
        header('HTTP/1.1 404 Not Found');
        echo 'Product not found';
    }
}

// Define endpoint to create a new product
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_SERVER['REQUEST_URI'] == '/products') {
    $data = json_decode(file_get_contents('php://input'), true);
    $name = $data['name'];
    $description = $data['description'];
    $price = $data['price'];
    
    $query = "INSERT INTO products (name, description, price) VALUES ('$name', '$description', $price)";
    $result = mysqli_query($connection, $query);
    
    if ($result) {
        header('HTTP/1.1 201 Created');
        echo 'Product created';
    } else {
        header('HTTP/1.1 500 Internal Server Error');
        echo 'Error creating product';
    }
}

Build A Rest API With PHP

Now, let’s dive into how to build a REST API with PHP. The first step is to decide what data you want to expose through your API. Once you have identified the data, you need to design the API endpoints. An endpoint is a URL that represents a specific resource, and it is used to interact with the API.

While doing this, be very aware of using the request Method. (GET|POST)

For example, let’s say you want to build a REST API for a product catalog. You might have endpoints for retrieving a list of products, creating a new product, updating an existing product, and deleting a product. The URLs for these endpoints might look like this:

  • GET /products
  • POST /products
  • PUT /products/{id}
  • DELETE /products/{id}

Once you have designed your endpoints, you can implement them in PHP. And I would suggest that you can use Frameworks like Laravel,Symphony, and Slim because these frameworks help in handling the requests, responses, routing, and authentication. For example: In Laravel you can use the JWT library for best security practices.

Best practices for building a REST API with PHP

Now, let’s talk about some best practices for building a REST API with PHP. These practices will help ensure that your API is secure, reliable, and easy to use.

Use HTTPS

Always use HTTPS for your API to encrypt the data in transit and prevent unauthorized access. HTTPS is now considered the standard for secure communication on the web.

Use HTTP status codes

Use HTTP status codes to indicate the result of an API request. For example, a successful request should return a 200 OK status code, while an error should return a 400 or 500 status code.

Use JSON for data exchange

Use JSON (JavaScript Object Notation) as the format for exchanging data between the API and the client. JSON is a lightweight and widely supported format that is easy to parse and serialize.

Version your API

Version your API to provide backward compatibility and allow for future changes. You can include the API version in the URL or in the HTTP headers.

for example, if you are using laravel you can do like this:

$app->group('/api/v1', function () use ($app) {
    $app->get('/products', 'getProducts');
    $app->post('/products', 'addProduct');
    $app->put('/products/{id}', 'updateProduct');
    $app->delete('/products/{id}', 'deleteProduct');
});

Implement authentication and authorization

Implement authentication and authorization to restrict access to your API and protect sensitive data. You can use OAuth 2.0, JWT (JSON Web Tokens), or basic authentication.

I hope this article will help you understand Rest Api in a much better way.

Service Classes In Laravel

Conclusion

n conclusion, Building a REST API with PHP requires careful planning to best practices. By following these practices, you can create a secure, reliable, and easy-to-use API that can be integrated with other systems and applications.

Leave a Comment