Open In App

CRUD Operation in REST API using PHP

Last Updated : 10 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

What is a REST API?

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.
Screenshot-2024-09-09-171044
Type in search box xampp Control Panel and click on open

Step 2: Create a MySQL Database

Access phpMyAdmin

  • In the XAMPP Control Panel, click "Admin" next to MySQL. This will open phpMyAdmin.
Screenshot-2024-09-09-171501
  • In phpMyAdmin, click on the "Databases" tab.
image1
  • Create a new database called myapi_db.
image2
Enter database name myapi_db and click on Create button.

Step 3: Create Table

  • After creating the database, select myapi_db.
  • Create a users table with the following fields: id, name, and email.
image4
table model
  • After save we will insert sample data into our users table:
INSERT INTO users (name, email) VALUES
('John Doe', 'john@example.com'),
('Jane Doe', 'jane@example.com'),
('Alice Smith', 'alice@example.com'),
('Bob Brown', 'bob@example.com'),
('Charlie Black', 'charlie@example.com');
  • Copy above query and paste into your database console and press Ctrl+Enter.
Screenshot-2024-09-09-224728
command
  • After inseting sample data into users table:
Screenshot-2024-09-09-224506
Table

Steps to create the PHP REST API

Step 1: Create Project Folder

  • 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.
PHP
//  config/database.php
<?php
$host = 'localhost';
$db_name = 'myapi_db';
$username = 'root';
$password = '';

try {
    $conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
    echo "Connection error: " . $exception->getMessage();
}
?>

Step 3: Create the API File

  • Inside the my-php-api folder, create a new folder called api and a file called users.php
PHP
// api/users.php
<?php
require_once __DIR__ . '/../config/database.php';

header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];

switch($method) {
    case 'GET':
        // Handle GET request (Retrieve Users)
        $stmt = $conn->query("SELECT * FROM users");
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($users);
        break;

    case 'POST':
        // Handle POST request (Create User)
        $data = json_decode(file_get_contents("php://input"));
        $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':name', $data->name);
        $stmt->bindParam(':email', $data->email);
        if($stmt->execute()) {
            echo json_encode(['message' => 'User created successfully']);
        }
        break;

    case 'PUT':
        // Handle PUT request (Update User)
        $data = json_decode(file_get_contents("php://input"));
        $sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':name', $data->name);
        $stmt->bindParam(':email', $data->email);
        $stmt->bindParam(':id', $data->id);
        if($stmt->execute()) {
            echo json_encode(['message' => 'User updated successfully']);
        }
        break;

    case 'DELETE':
        // Handle DELETE request (Delete User)
        $data = json_decode(file_get_contents("php://input"));
        $sql = "DELETE FROM users WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $data->id);
        if($stmt->execute()) {
            echo json_encode(['message' => 'User deleted successfully']);
        }
        break;

    default:
        http_response_code(405); // Method Not Allowed
        break;
}
?>

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:

  • Access Postman in your browser.
  • Click Postman Agent then select Desktop Agent.
image5

1. Testing the GET Request (Read Users)

  • Open Postman and create a new request.
  • Select the GET method and enter the URL: http://localhost/my-php-api/api/users.php.
  • Click "Send" to fetch all users.

2. Testing the POST Request (Create User)

  • In Postman, select the POST method and enter the URL: http://localhost/my-php-api/api/users.php.
  • In the "Body" tab, select "raw" and "JSON" format.
  • Enter the following JSON:
{
"name": "New User",
"email": "newuser@example.com"
}
  • Click "Send" to create a new user.

3. Testing the PUT Request (Update User)

  • In Postman, select the PUT method and enter the URL: http://localhost/my-php-api/api/users.php.
  • In the "Body" tab, select "raw" and "JSON" format.
  • Enter the following JSON to update the user:
{
"id": 1,
"name": "Updated User",
"email": "updated@example.com"
}
  • Click "Send" to update the user.

4. Testing the DELETE Request (Delete User)

  • In Postman, select the DELETE method and enter the URL: http://localhost/my-php-api/api/users.php.
  • 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.


Similar Reads

REST API using the Express to perform CRUD (Create, Read, Update, Delete)
In this article, we are going to learn how can we build an API and how can we perform crud operations on that. This will be only backend code and you must know JavaScript, NodeJs, Express.js, and JSON before starting out this. This Node.js server code sets up a RESTful API for managing student data. It provides endpoints for performing CRUD (Create
9 min read
CRUD Operation in MySQL Using PHP, Volley Android - Read Data
In the previous article, we have performed the insert data operation. In this article, we will perform the Read data operation. Before performing this operation first of all we have to create a new PHP script for reading data from SQL Database. Prerequisite: You should be having Postman installed in your system to test this PHP script. Create a PHP
9 min read
CRUD Operation in MySQL Using PHP, Volley Android - Insert Data
It is known that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS. SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease, and flexibility of use. The application is used for a wide range of purposes, includ
10 min read
Difference Between REST API and RPC API
REST and RPC are design architectures widely used in web development to build APIs (Application Programming Interface). It is a set of instructions that permits two systems to share resources and services. The client creates a request to the server that responds to it with data in JSON or XML format. REST APIs It stands for Representational State T
3 min read
Know the Difference Between REST API and RESTful API
APIs (Application Programming Interface) act as an interface between two applications to interact and provide the relevant data. It uses a set of protocols using which the operation is done. Salesforce was the first organization to officially launch API, followed by eBay and Amazon. Also, 60% of transactions made on eBay use their APIs. If we talk
5 min read
Difference between REST API and SOAP API
REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are the most common methods for communications These services enable web to communicate with the servers with HTTP protocol. REST is architectural style that works over HTTP for communication while SOAP is a protocol with strict standards and is helpful for complex syst
2 min read
Building a REST API with PHP and MySQL
This brief tutorial is a step-by-step guide on how to develop a REST API using PHP and MySQL. REST API will implement HTTP commands (Get, Post, Put, DELETE) and response will be in form of JSON. For development setup, we will be using the XAMPP while for testing of the API, we will use the Postman app. Steps to Build REST API with PHP and MySQLStep
4 min read
How to create a REST API using Java Spring Boot
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
How to create Covid19 Country wise status project using REST API ?
Today, All Countries in the world fighting with Coronavirus. Every day, Coronavirus cases rising rapidly. It is important for all to keep track of COVID Cases daily and should try to keep himself/herself safe. We have made small web apps that will tell you the total no of cases, new cases, new death, recovery, etc. to the user. You have to just ent
7 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Application’s functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and interact with each other.API is a service created
15+ min read
Build a document generator with Express using REST API
In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Document Generator using Node and Express, two powerful
2 min read
Consuming a REST API ( Github Users ) using Fetch - React Client
In this article, you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user's public information with their username. You can find the API reference and source code links at the end of this article. Prerequisites:NodeJS or NPMReactJSSteps to Create the React A
3 min read
How to create a REST API using json-server npm package ?
This article describes how to use the json-server package as a fully working REST API. What is json-server? json-server is an npm(Node Package Manager) module/package, used for creating a REST API effortlessly. Data is communicated in JSON(JavaScript Object Notation) format between client and server. Installation: Execute the below command in your
4 min read
Creating a REST API Backend using Node.js, Express and Postgres
Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications. This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API. Installation R
4 min read
Node.js Building simple REST API in express
Let's have a brief introduction about the Express framework before starting the code section:Express: It is an open-source NodeJs web application framework designed to develop websites, web applications, and APIs in a pretty easier way. Express helps us to handle different HTTP requests at specific routes.As it is NodeJs web framework so make sure
2 min read
REST API in Hyperledger
REST, or Representational State Transfer, is an architectural style for building web services. It is based on a set of principles that define how web resources should be defined, accessed, and manipulated. One of the key principles of REST is the use of the HTTP protocol for communication between clients and servers. This means that REST APIs are b
7 min read
Best Coding Practices For Rest API Design
JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a paym
10 min read
Why REST API is Important to Learn?
API... Being a developer what comes to your mind first when you listen to this word... JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, or something else... If you're familiar with the above word then surely you might have worked on some kinds of APIs (especially those who are experienced developers) in yo
8 min read
Consuming a Rest API with Axios in Vue.js
Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP client library. Similar to JavaScript fetch API, it use
2 min read
How to generate document with Node.js or Express.js REST API?
Generating documents with Node and Express REST API is an important feature in the application development which is helpful in many use cases. In this article, we will discuss two approaches to generating documents with Node.js or Express.js REST API. Table of Content Document Generation using PdfKit libraryDocument Generation using Puppeteer libra
3 min read
How to Create A REST API With JSON Server ?
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Request Returns a List of all UsersPOST Request to c
4 min read
REST API Introduction
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology bec
5 min read
HTTP REST API Calls in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. We already know about the importance of HTTP REST
13 min read
REST API Call to Get Location Details in Vue.js
In this article, we will know the REST API call to get the location details in VueJS, along with understanding its implementation through the examples. VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developer. It is compatible with other libraries
7 min read
What is an Idempotent REST API?
Idempotent REST API means that if the same request is made a number of times then it will have the same impact as making the request just once. Lastly, the idempotent characteristic is essential for creating dependable and linear web services when clients might attempt to send the same request multiple times due to network instability. This is due
7 min read
What is REST API in Node.js ?
REST (Representational State Transfer) is an architectural style for designing networked applications. A RESTful API is an API that adheres to the principles of REST, making it easy to interact with and understand. In this article, we'll explore what REST API is in the context of Node.js, its principles, and how to create one. Table of Content Unde
11 min read
How to Build a REST API with Next.js 13?
Next.js is the most widely used React framework. Next.js 13.2 introduced a new file-based routing mechanism, called App Router, for building React frontend and serverless backend. In this article, we will be building a simple REST API using Next.js Route Handlers Table of Content Next.js Route HandlersNext.js project initializationBuilding REST API
7 min read
GitHub REST API
The GitHub REST API allows developers to interact with GitHub programmatically, enabling you to manage repositories, handle issues, automate workflows, and integrate GitHub with other tools and platforms. Whether you're building an application, automating repetitive tasks, or just curious about how GitHub works behind the scenes, the REST API is a
4 min read
REST API Endpoints For Git Tags
In Git, tags are used to mark specific commits as important, typically signifying a release. Unlike branches, tags are immutable references, making them perfect for marking stable points in your repository’s history, such as version releases. Why Use REST API for Git Tags?Interacting with Git tags via REST APIs allows for easy integration with CI/C
3 min read
REST API Endpoints For GitHub Actions Variables
GitHub Actions is used to automate workflows, build, test, and deploy code. To make workflows more dynamic and secure, GitHub Actions allows you to use variables, which can store data like configuration values, secrets, or other necessary information. GitHub exposes a REST API to manage these variables efficiently, providing developers with full co
5 min read
Article Tags :
three90RightbarBannerImg