How to make REST API PHP

Make a REST API in PHP with an example: Learn how to create a REST API in PHP using a simple example.

Creating a RESTful API in PHP

Creating a RESTful API in PHP is a relatively simple process. With a few lines of code, you can quickly and easily create a basic API that can be used to retrieve, update, and delete data from a database. In this article, we will look at how to create a basic RESTful API in PHP that can be used to access and manipulate data from a database.

1. Connecting to a Database

The first step in creating a RESTful API in PHP is to connect to a database. This can be done using the built-in mysqli_connect function. This function takes three parameters: a hostname, a username, and a password. Once the connection is established, you can use the mysqli_select_db function to select the database you wish to use for your API.


// Connect to database
$db = mysqli_connect("localhost", "username", "password");

// Select database
mysqli_select_db($db, "my_database");

2. Writing the API

Once the database is connected, you can begin writing the API. The API should have a few main components: a method to retrieve data, a method to create data, a method to update data, and a method to delete data. Each of these methods should be accessible via an HTTP request, and should return a JSON response.

To retrieve data, you can use an HTTP GET request. This request should take the form of a URL with an optional query string. For example, if you wanted to retrieve a list of users, you could use the following URL:


GET /users

You can also use the query string to filter the results. For example, if you wanted to retrieve only users with a certain name, you could use the following URL:


GET /users?name=John

To create data, you can use an HTTP POST request. This request should take the form of a URL with an optional body containing the data to be created. For example, if you wanted to create a new user, you could use the following URL:


POST /users

The body of the request could then contain the user data, such as name, email address, etc. You can also use the body to provide additional information, such as an API key for authentication.

To update data, you can use an HTTP PUT request. This request should take the form of a URL with an optional body containing the data to be updated. For example, if you wanted to update a user's name, you could use the following URL:


PUT /users/123

The body of the request could then contain the new name, as well as any other data that needs to be updated. You can also use the body to provide additional information, such as an API key for authentication.

Finally, to delete data, you can use an HTTP DELETE request. This request should take the form of a URL with an optional body containing the data to be deleted. For example, if you wanted to delete a user, you could use the following URL:


DELETE /users/123

The body of the request could then contain the user's ID, as well as any other data that needs to be deleted. You can also use the body to provide additional information, such as an API key for authentication.

3. Writing the Code

Now that we have our API methods defined, we can begin writing the code. The first step is to create a function for each method that will handle the request and return a JSON response. For example, the following function will handle a GET request for retrieving data from the database:


function getData($db, $query) {
    $result = mysqli_query($db, $query);
    if ($result) {
        $data = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
        return json_encode($data);
    } else {
        return false;
    }
}

This function takes a database connection and a query as parameters. It then executes the query and returns the resulting data as a JSON string. If the query fails, it returns false.

The other API methods can be written in a similar way. For example, the following function will handle a POST request for creating data in the database:


function createData($db, $query, $data) {
    $result = mysqli_query($db, $query);
    if ($result) {
        $id = mysqli_insert_id($db);
        return json_encode(array("id" => $id));
    } else {
        return false;
    }
}

This function takes a database connection, a query, and the data to be inserted as parameters. It then inserts the data into the database and returns the ID of the newly created record as a JSON string. If the query fails, it returns false.

Once the functions for each API method have been written, you can use the $_SERVER['REQUEST_METHOD'] variable to determine which method was used, and call the appropriate function. For example:


// Get request method
$method = $_SERVER['REQUEST_METHOD'];

// Handle request
switch ($method) {
    case 'GET':
        // Handle GET request
        $data = getData($db, $query);
        break;
    case 'POST':
        // Handle POST request
        $data = createData($db, $query, $data);
        break;
    case 'PUT':
        // Handle PUT request
        $data = updateData($db, $query, $data);
        break;
    case 'DELETE':
        // Handle DELETE request
        $data = deleteData($db, $query);
        break;
    default:
        // Return error
        $data = array("error" => "Invalid request method");
        break;
}

// Return response
echo $data;

This code checks the request method, and calls the appropriate function. It then returns the response as a JSON string. This is a very basic example, but it should give you a good starting point for creating your own RESTful API in PHP.

Answers (0)