How To Make Rest API In PHP | AV Coding
Hey guys welcome to AV Coding
Today we will learn how to make rest api in php with also using php basic functions as well as pdo functions.
PHP file_get_contents() Documentation: https://www.php.net/manual/en/function.file-get-contents.php
HTTP Response Codes Documentation: https://www.restapitutorial.com/httpstatuscodes.html
The complete code is explained in the video below and the source code is provided below.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
$db['db_host'] = "localhost";
$db['db_user'] = "root";
$db['db_pass'] = "";
$db['db_name'] = "avcoding";
$connection = mysqli_connect($db['db_host'], $db['db_user'],$db['db_pass'],$db['db_name']);
$query = "SET NAMES utf8";
mysqli_query($connection,$query);
//If Getting Data From User
$data = json_decode(file_get_contents("php://input"));
$data->key
// for eg:- json data is like
// {
// name: 'av',
// country: 'india'
// }
$data->name
$data->country
//Save or update data using normal query and using this data
//Send Response of success by making array as below
// If uploading files just use
// $_FILES['name of input']
// $_FILES[$data->key]
// And set headers Content-Type: multipart/form-data
// If Sending Data to User
// Create array by fetching data from database using normal queries
$data = array(
"name" => $name,
"country" => $country,
);
// set response code - 200 OK
http_response_code(200);
// show products data in json format
echo json_encode($data);
?>
Hope You Liked This Blog. Share, Comment, Subscribe And Press The Bell Icon In The Bottom Right Side For More Code Feeds.
0 Comments