Create a REST API in PHP with MySQL

In this tutorial, we will explain to you how to create a REST API in PHP with MySQL. Before we start, you might need to know about the REST API and how it works.

What is the REST API & How it works

REST stands for Representational State Transfer, REST API used for creating web services that can be accessed on different applications and created with CRUD (Create, Read, Update, Delete) operations. REST uses HTTP methods like GET, POST, PUT and DELETE to perform operations.

  • GET – To retrieve information.
  • POST – To create a new record.
  • PUT – To update existing records.
  • DELETE – To delete records.

In the REST API, we can get responses in JSON or XML format but we will use the JSON format because it is lightweight and easy to perform the parsing. Here, we will create a REST API to get customer data by passing the customer id and in the next article, we will consume it using a small example in PHP.

Steps to create a REST API in PHP with MySQL

  1. Create database table
  2. Connect database
  3. Create a file for REST API
  4. Rewrite the API URL
  5. Output

1. Create database table

We will create a customer table for a small example and for that we have created a demo database in MySQL. Run the following script to create a table in the database.

You can insert some sample records to the table for REST API testing.

2. Connect database

Now, we have to create a connection.php file and add the following code to connect the database.

connection.php

3. Create a file for REST API

In the next step, we will create an api.php file at the root level of the directory to create a REST API and add the following code in that file.

api.php

Now we can make an HTTP GET request and get the customer data by passing the customer id. You can run the following link to get the customer data.

Output:

4. Rewrite the API URL

Now, we need to rewrite the above URL using .htaccess file because it’s not user friendly.

.htaccess

After adding the above code in .htaccess file, we can retrieve the customer data by browsing the following URL and get the same output.

Output

Run the above given URLs in the browser to check the GET API.

Output - 1 - Create a REST API in PHP with MySQL - Clue Mediator
Output – 1 – Create a REST API in PHP with MySQL – Clue Mediator
Output - 2 - Create a REST API in PHP with MySQL - Clue Mediator
Output – 2 – Create a REST API in PHP with MySQL – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

  1. V3N0M says:

    Please escape the parameters that run into the script via GET, otherwise this is highly dangerous and negligent!!

Leave a Reply

Your email address will not be published. Required fields are marked *