The acronym of API is Application Programming Interface. And Create simple API in PHP is a very simple and easy process to do. API is a set of code that allows data transmission between one software to another. Software that wants to access information, calls the API with data requirements. Let us start Creating API in PHP
API consists of two major components
- Technical specification describing the data exchange options between solutions with the specification done in the form of a request for processing and data delivery protocols
- The software interface is written to the specification that represents it
Types of API by Availability:
- Private APIs
- Partner APIs
- Public APIs
Types of API by Use cases:
- Database APIs
- Operating systems APIs
- Remote APIs
- Web APIs
Steps to create API in PHP
1. Open Xampp and start Apache Server and MySQL.
Download XAMPP: https://www.apachefriends.org
2. Open MySQL admin in the browser. And Create a new Database.
3. Then Give the Table Name.
4. Give the table name and other attributes of the column.
5. Insert some dummy that in the Database.
6. Then Create a new api.php file inside the htdocs folder.
7. And write this code to connect to the Database.
<?php
$con = mysqli_connect("localhost","root","","API_DATA");
if($con)
{
echo "DB Connected";
}
else
{
echo "DB Connection Failed";
}
?>
If the connection with the database is successfully established then the “DB Connected” message will be displayed in the output. If not then “DB Connection Failed”.
8. Now inside the If condition we have to fetch the Row from the Database.
if($con)
{
$sql = "select * from data";
$result = mysqli_query($con,$sql);
if($result)
{
while($row = mysqli_fetch_assoc($result))
{
}
}
}
$sql variable stores the query to select all data from the Database. We call mysqli_query() to execute the query. We get the result to the variable $result.
11. Create an array to store the result fetched from the Database.
$response = array();
12. Now inside the while loop assign the value of the row to the variable we created. We have to create a variable $i and initialize it to zero then increment it at the end of the loop.
if($con)
{
$sql = "select * from data";
$result = mysqli_query($con,$sql);
if($result)
{
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
$response [$i]['id'] = $row['id'];
$response [$i]['name'] = $row['name'];
$response [$i]['age'] = $row['age'];
$response [$i]['email'] = $row['email'];
$i++;
}
}
}
13. Now print fetched Data in JSON format.
echo json_encode($response, JSON_PRETTY_PRINT);
14. Add Header Content-Type for JSON.
header ("Content-Type: JSON");
In this article, we have seen how we can create a simple API in PHP to fetch data from MySQL with simple steps and the right way to do it. Feel free to ask anything related to this article in the comment section, we will be happy to help you.
Read more: