A REST (Representational State Transfer) API allows communication between a client and a server through HTTP requests. PHP, a widely used server-side scripting language, is well-suited for creating REST APIs due to its simplicity and rich ecosystem. This article provides a step-by-step guide on building a REST API in PHP, covering various approaches, detailed explanations, syntax, examples, and output. Additionally, we'll discuss the prerequisites, provide a structured folder setup, demonstrate the process of creating and testing a basic REST API, and include steps for creating a database with sample data.
These are the following topics that we are going to discuss:
A REST API (Representational State Transfer Application Programming Interface) is an architectural style that allows communication between different software applications over the HTTP protocol. REST APIs use standard HTTP methods such as GET, POST, PUT, DELETE, etc., to perform operations on resources, which are typically represented in formats like JSON or XML. REST APIs are stateless, meaning each request from a client must contain all the information needed to understand and process the request, with no session state stored on the server
Steps to Set Up XAMPP
Step 1: Download and Install XAMPP
Download XAMPP from Apache Friends.
Follow the installation wizard to install XAMPP.
Once installed, open the XAMPP Control Panel and start the Apache and MySQL services.
Navigate to the htdocs folder inside the XAMPP installation directory (e.g., C:\xampp\htdocs).
Create a new folder called my-php-api.
Command:
mkdir my-php-api
Step 2: Create a Database Connection File
Inside the my-php-api folder, create a new folder called config.
Inside the config folder, create a file called database.php.
Step 3: Create the API File
Inside the my-php-api folder, create a new folder called api and a file called users.php
Test the API Using Postman
Now that the API is ready, we can test the CRUD operations using Postman. Before sending request using postman we have to set up desktop agent because we are testing locally so follow the given below steps:
In Postman, select the DELETE method and enter the URL:
In the "Body" tab, select "raw" and "JSON" format.
Enter the following JSON to delete the user:
{ "id": 1 }
Click "Send" to delete the user.
Conclusion
In this article, we demonstrated how to build a simple REST API using PHP and MySQL, covering basic CRUD operations. We used XAMPP to run our local server and MySQL database, and Postman to test the API endpoints. By following the steps outlined in this guide, you can easily extend the API and add more functionalities based on your project requirements.