SlideShare a Scribd company logo
1 of 21
Download to read offline
How to develop an API with
PHP, JSON, and POSTMAN in
9 Steps
by Pawan
Table of Contents
● Introduction
● What is an API?
● Why should you develop an API with PHP?
● What is JSON?
● What is POSTMAN?
● The process to develop an API
○ Establish Database
○ Provide Data in Database
○ Connect Database with PHP
○ Build API – GET Request
○ Test API with POSTMAN
○ Create API – GET Single data
○ Develop an API – POST Request for Insert & Update
○ Build API – DELETE Request
○ Search API – GET Request
● Conclusion
Introduction
Do you want to develop an API with PHP, JSON, and POSTMAN?
Or are you simply looking for a way to build API for your Android App or IOS
app?
Look no further!
In this tutorial, I will show you how to do just that!
We’ll go over the basics of each technology, we are using. Then dive into how
to use them together to create API for your need. By the end of this tutorial,
you’ll be able to create your API with PHP and JSON.
Before diving in, might I recommend a fantastic free editor that I love to use?
Check out this post for more details.
What is an API?
So you want to build API or maybe multiple APIs?
First, let’s understand what is an API and why we rely on them in modern web
app development.
The official definition you will find is: API stands for Application
Programming Interface.
What does that mean?
In simple words, without techy jargon, an API is a piece of code you write, that
allows two different pieces of software to communicate with each other.
API is just a way to allow two different software to connect.
Why use API though? Simple. Have you ever used an android app where you
are fetching and sending data most likely you have. Then you have already
used an API.
Yeah! API is everywhere on the internet!
With an API you connect databases like MySQL or MongoDB (or any other) to
any frontend interface as an Android app or Web app. And foremost, APIs can
be incredibly fast and easy to use.
Learning how API works before developing an API is crucial
So you understand the basics of API and how it works behind the scene. Let’s
jump into the technology we are going to use in our API build.
Why should you develop an API with
PHP?
While there are many languages & frameworks for creating APIs, we are
going to use PHP for this purpose.
But why?
Let me answer the question in detail:
● PHP-based APIs are extremely easy to deploy. You don’t need
to host the API on a separate physical server like Java or C.
Which reduces overall cost.
● Despite being free, PHP is very powerful and you can use it to
create very complex APIs.
● Even if you haven’t ever coded a programming language, PHP is
easier to understand and learn. Remember HTML and CSS
are structuring/styling languages, not programming ones.
So now you know why I chose PHP as the backbone of my API. Let’s look at
other technology and tool we need to build API.
What is JSON?
If you ever worked with App Developer, as I have, you will love how much they
appreciate the JSON.
Why?
I know I am very fond of why question. But it’s vital to understand the reason
behind why JSON dominates the API building market. Let me explain:
● JSON, as you must know, stands for JavaScript Object
Notation.
● JSON is not JavaScript. Please be careful not to confuse them.
● Yes, it looks similar to JavaScript objects but that’s because
JSON shares a common codebase with ECMAScript, C++, and
even C. But JSON is an independent and complete language
in itself.
● It’s an ultra-lightweight data-interchange format.
● It’s language-independent, platform-independent, and most
importantly, developer-friendly. The only language that comes
close to competing is XML but it has its issues.
● JSON data can be written in any editor, sent over the network,
and parsed by any platform. It may not seem that important in a
modern environment where we have high-processing systems
available. But in certain situations, JSON adaptability is a
lifesaver.
See how vital JSON is for our process to create API. Let’s jump to the last tool
we need to get started.
What is POSTMAN?
Before you joke, no I am not talking about the Postman who delivers letters.
Our POSTMAN is an extremely powerful and necessary tool for testing and
resolving bugs with our create API in PHP process.
So is it an absolute necessity? The answer would be No.
But other ways of testing your build API process are too time-consuming and
not much accurate. POSTMAN is the tool all professionals rely upon.
In past, POSTMAN used to be a browser extension but now it’s a full-fledged
software you can download. We only need the free version for our needs.
POSTMAN is the best tool to build API and test it.
The process to develop an API
Now that we have acquainted with all the tools we will need. Let’s jump into
the process of building API:
Establish Database
We build the database first. I will name my database “students“. Feel free to
name your database anything. But keep a note of it as you will need it later on.
Next, we create a table “studentdata” which will hold our data. To make the
table and its field quickly. Run the below SQL command:
CREATE TABLE `studentdata` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`age` int(5) NOT NULL,
`city` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
If you don’t know how to run SQL commands in PHPMyAdmin. Read my
previous article, I’ve explained there how to run SQL.
Now your database has a table and looks like this:
The process to build API database in phpMyAdmin.
Provide Data in Database
Now that we have a database and a table let us insert some data by SQL for
now. Don’t worry we will create a process in PHP to insert data through our
API. But that comes later.
INSERT INTO `studentdata` (`id`, `name`, `age`, `city`) VALUES
(2, 'Suresh', 26, 'Chennai'),
(3, 'Abhimanyu', 19, 'Kolkata'),
(4, 'Raj', 25, 'Kanpur'),
(5, 'Subash', 27, 'Bhopal'),
(7, 'Amir', 35, 'Imphal');
For now, we have some data in our database that we can interact with, when
we build our API.
Connect Database with PHP
Now we connect to our database with PHP. For this purpose, I created the
“connect.php” file.
Note: “.php” is our extension for PHP files.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'students');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
Build API – GET Request
Now we start coding with PHP. So bring your favorite code editor as I started
up with mine. Let’s write the first API file that will fetch everything from our
database.
Filename: “api_fetch_all.php“.
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
include 'connect.php';
$sql = "select * from studentdata";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//mysqli_fetch_all gives us the data in 2D array format.
// It's second parameter decide whether its assoc array or
indexed. Or maybe both
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
} else {
echo json_encode(['msg' => 'No Data!', 'status' => false]);
}
?>
Let me explain what we wrote and why:
● Our first line “header(‘Content-Type: application/json’)“ is telling
our file that we are using the JSON data format to exchange
data. Without this line of code, our API will never work.
● The next header line is simply allowing our API file to access
data. Sometimes you will see developers skip this line. And
sometimes that’s okay. But for the best result and to avoid any
future error, we did define it.
● Now, we ran the standard PHP code to select all data from the
database. Then fetched that data and stored it in our “$data”
variable.
● Using the famous PHP method “json_encode()“, we convert our
data into JSON format. And “echo” this JSON data.
● Lastly, we encoded an error msg and status, just in case our data
failed to be obtained.
If you have reached this point. Congratulations!
You are halfway done with learning the basics of how to create API in PHP.
We have also built our first API file so let us test it with POSTMAN.
Test API with POSTMAN
Testing API with POSTMAN might seem daunting at first. But no worries, I will
guide you through that process.
● Open your POSTMAN app and click the “+” icon where it says
“Untitled Request“.
Open first your “Untitled Request”
● Enter your API URL in the “URL-send” and set it to “GET”
● In the lower tab choose the header section. Enter header to
content-type: application/JSON. Then hit Enter button.
● If done everything, you will see the JSON response in the
downward part.
Now we have completed our first API. This API will fetch all data for us from
the database in JSON format. Let’s continue the rest of the process of
developing an API.
Create API – GET Single data
Now let’s code our API file which will fetch single data by id as reference.
Filename: api_fetch_single.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
// This is the data which is being sent to request a single data.
// Since we know this request will be in json format we must
decode before passing it into our php logic
// file_get_contents is reading file into a string.
// "php://input" is special key which insure that we can get any
format of data. Even if its raw data.
// True argument of json decode makes sure that we get response in
assoc array
$data = json_decode(file_get_contents("php://input"), true);
// we are getting our passed data in $data array. But to ensure
securty we will change name of id to sid. Remember we are being
requested data on basis of sid after all.
$student_id = $data['sid'];
include 'connect.php';
$sql = "select * from studentdata where id = $student_id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//mysqli_fetch_all gives us the data in 2D array format.
// It's second parameter decide whether its assoc array or
indexed. Or maybe both
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
} else {
echo json_encode(['msg' => 'No Data!', 'status' => false]);
}
?>
Unlike the previous API where we were fetching every data in the table, now
we are targeting a specific one.
Also, we provide code “file_get_contents” which allows our reading file into a
string. And “php://input” is a special key that ensures that we can get any
format of data. Even if it’s raw data.
Similarly, we will create API files for POST and DELETE requests too.
Develop an API – POST Request for Insert &
Update
First, let’s learn how to build a POST request API that will insert our data into
the database.
Filename: api_insert.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Methods, Access-Control-Allow-Headers,
Authorization, X-Requested-With');
// Since we are inserting data we pass two extra headers.
// 1st allow us to set the method of insert. i.e. POST in rest api
// 2nd determines which type of headers can be sent. It's a
secuirty header.
// 'Authorization' is set for authorizing insert data. While
'X-Requested-With' is set for passing data as json
$data = json_decode(file_get_contents("php://input"), true);
$sname = $data['sname'];
$sage = $data['sage'];
$scity = $data['scity'];
include 'connect.php';
$sql = "insert into studentdata (name, age, city) values
('$sname', '$sage', '$scity')";
if (mysqli_query($conn, $sql)) {
echo json_encode(['msg' => 'Data Inserted Successfully!',
'status' => true]);
} else {
echo json_encode(['msg' => 'Data Failed to be Inserted!',
'status' => false]);
}
?>
Next, we are up for Update Requests. Which again will be done with POST
Request but with little modifications.
Filename: api_update.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: PUT');
header('Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Methods, Access-Control-Allow-Headers,
Authorization, X-Requested-With');
// To update is similar to insert. Except in rest api update
request is done throough PUT method
$data = json_decode(file_get_contents("php://input"), true);
$sid = $data['sid'];
$sname = $data['sname'];
$sage = $data['sage'];
$scity = $data['scity'];
include 'connect.php';
$sql = "update studentdata set name = '$sname', age = '$sage',
city = '$scity' where id = '$sid'";
if (mysqli_query($conn, $sql)) {
echo json_encode(['msg' => 'Data Updated Successfully!', 'status'
=> true]);
} else {
echo json_encode(['msg' => 'Data Failed to be Updated!', 'status'
=> false]);
}
?>
Remember while updating, we are providing a specific id with our
“update-data“.
Last we have only the Delete and Search API part left. Let’s keep going.
Build API – DELETE Request
When writing Delete Request, we add two new headers type.
● header(‘Access-Control-Allow-Methods: DELETE’) – allow us to
set our API to delete files as needed. Without it, you will run into
errors.
● Next headers allow us to give more control of files to API queries.
It’s recommended to add them.
Filename: api_delete.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE');
header('Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Methods, Access-Control-Allow-Headers,
Authorization, X-Requested-With');
// To delete in rest api, we use DELETE method
$data = json_decode(file_get_contents("php://input"), true);
$sid = $data['sid'];
include 'connect.php';
$sql = "delete from studentdata where id = '$sid'";
if (mysqli_query($conn, $sql)) {
echo json_encode(['msg' => 'Data Deleted Successfully!', 'status'
=> true]);
} else {
echo json_encode(['msg' => 'Data Failed to be Deleted!', 'status'
=> false]);
}
?>
Before finalizing, do test your API with POSTMAN.
And now let’s move to the last API file of the day. It’s quite an important one
though, so stay alert.
Search API – GET Request
Filename: api_search.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
$data = json_decode(file_get_contents("php://input"), true);
$searchterm = $data['search'];
include 'connect.php';
$sql = "select * from studentdata where name like
'%$searchterm%'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
} else {
echo json_encode(['msg' => 'No Data Found to search query!',
'status' => false]);
}
?>
See what your search should look like in the below image:
Search API with GET/POST Request
Note: Search functionality in an API can be developed by either GET or POST
request method. In GET method case we pass our search values to the URL.
In the POST method, we use the normal JSON input.
Conclusion
So there you have it!
A quick and easy guide on how to develop an API with PHP, JSON, and
POSTMAN. I hope this has been helpful for you. With this detailed guide at
your side, we at Be Problem Solver believe you feel more confident to develop
APIs.
In upcoming posts, I will show you how to use this API and other third-party
APIs in projects.
If you have any questions or comments, then feel free to reach out. And do
check out my other post about adding jazz to your website with page scroll
animations.
Ta-da! Guys and Gals! Happy coding!

More Related Content

What's hot

Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...
Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...
Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...Simplilearn
 
Declarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingDeclarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingFlorian Stefan
 
How to Automate API Testing
How to Automate API TestingHow to Automate API Testing
How to Automate API TestingBruno Pedro
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
B4USolution_API-Testing
B4USolution_API-TestingB4USolution_API-Testing
B4USolution_API-Testingb4usolution .
 
Curso Treinamento Automação de testes com Selenium Qualister
Curso Treinamento Automação de testes com Selenium QualisterCurso Treinamento Automação de testes com Selenium Qualister
Curso Treinamento Automação de testes com Selenium QualisterQualister
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Presentation for soap ui
Presentation for soap uiPresentation for soap ui
Presentation for soap uiAnjali Rao
 
Automate REST API Testing
Automate REST API TestingAutomate REST API Testing
Automate REST API TestingTechWell
 
API Testing Presentations.pptx
API Testing Presentations.pptxAPI Testing Presentations.pptx
API Testing Presentations.pptxManmitSalunke
 
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)SangIn Choung
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answersbhanuadmob
 

What's hot (20)

Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...
Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...
Puppet Tutorial | Puppet Tutorial For Beginners | Puppet Configuration Manage...
 
Declarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingDeclarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive Programming
 
How to Automate API Testing
How to Automate API TestingHow to Automate API Testing
How to Automate API Testing
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Api Testing
Api TestingApi Testing
Api Testing
 
API Testing
API TestingAPI Testing
API Testing
 
Selenium WebDriver com Docker
Selenium WebDriver com DockerSelenium WebDriver com Docker
Selenium WebDriver com Docker
 
B4USolution_API-Testing
B4USolution_API-TestingB4USolution_API-Testing
B4USolution_API-Testing
 
Curso Treinamento Automação de testes com Selenium Qualister
Curso Treinamento Automação de testes com Selenium QualisterCurso Treinamento Automação de testes com Selenium Qualister
Curso Treinamento Automação de testes com Selenium Qualister
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
POSTMAN.pptx
POSTMAN.pptxPOSTMAN.pptx
POSTMAN.pptx
 
Presentation for soap ui
Presentation for soap uiPresentation for soap ui
Presentation for soap ui
 
Automate REST API Testing
Automate REST API TestingAutomate REST API Testing
Automate REST API Testing
 
API Testing Presentations.pptx
API Testing Presentations.pptxAPI Testing Presentations.pptx
API Testing Presentations.pptx
 
Api testing
Api testingApi testing
Api testing
 
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answers
 
Spring boot
Spring bootSpring boot
Spring boot
 

Similar to How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf

Create a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of codeCreate a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of codeYashobanta Bai
 
Building native mobile apps with word press
Building native mobile apps with word pressBuilding native mobile apps with word press
Building native mobile apps with word pressNikhil Vishnu P.V
 
WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!Evan Mullins
 
Proper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino DevelopersProper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino DevelopersMark Myers
 
How to insert json data into my sql using php
How to insert json data into my sql using phpHow to insert json data into my sql using php
How to insert json data into my sql using phpTrà Minh
 
WordCamp Wilmington 2017 WP-API Why?
WordCamp Wilmington 2017   WP-API Why?WordCamp Wilmington 2017   WP-API Why?
WordCamp Wilmington 2017 WP-API Why?Evan Mullins
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!Evan Mullins
 
API Integration in Web Application
API Integration in Web ApplicationAPI Integration in Web Application
API Integration in Web Applicationijtsrd
 
Open Event API
Open Event APIOpen Event API
Open Event APIAvi Aryan
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinGavin Pickin
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sOrtus Solutions, Corp
 
Php Interview Questions
Php Interview QuestionsPhp Interview Questions
Php Interview QuestionsUmeshSingh159
 
Top 7 Skills PHP Developer Must Have
Top 7 Skills PHP Developer Must HaveTop 7 Skills PHP Developer Must Have
Top 7 Skills PHP Developer Must HaveIndumathySK
 
Will be an introduction to
Will be an introduction toWill be an introduction to
Will be an introduction toSayed Ahmed
 
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Tom Johnson
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 

Similar to How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf (20)

Create a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of codeCreate a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of code
 
Building native mobile apps with word press
Building native mobile apps with word pressBuilding native mobile apps with word press
Building native mobile apps with word press
 
WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Birmingham 2016 - WP API, What is it good for? Absolutely Everything!
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
 
Proper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino DevelopersProper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino Developers
 
How to insert json data into my sql using php
How to insert json data into my sql using phpHow to insert json data into my sql using php
How to insert json data into my sql using php
 
WordCamp Wilmington 2017 WP-API Why?
WordCamp Wilmington 2017   WP-API Why?WordCamp Wilmington 2017   WP-API Why?
WordCamp Wilmington 2017 WP-API Why?
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
 
Web Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptxWeb Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptx
 
API Integration in Web Application
API Integration in Web ApplicationAPI Integration in Web Application
API Integration in Web Application
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Open Event API
Open Event APIOpen Event API
Open Event API
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api's
 
Php Interview Questions
Php Interview QuestionsPhp Interview Questions
Php Interview Questions
 
Top 7 Skills PHP Developer Must Have
Top 7 Skills PHP Developer Must HaveTop 7 Skills PHP Developer Must Have
Top 7 Skills PHP Developer Must Have
 
Day01 api
Day01   apiDay01   api
Day01 api
 
Will be an introduction to
Will be an introduction toWill be an introduction to
Will be an introduction to
 
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 

More from Be Problem Solver

Learn to build a CodeIgniter Login and Registration with source code.pdf
Learn to build a CodeIgniter Login and Registration with source code.pdfLearn to build a CodeIgniter Login and Registration with source code.pdf
Learn to build a CodeIgniter Login and Registration with source code.pdfBe Problem Solver
 
Image Converter script for PNG to JPG & JPG to PNG.pdf
Image Converter script for PNG to JPG & JPG to PNG.pdfImage Converter script for PNG to JPG & JPG to PNG.pdf
Image Converter script for PNG to JPG & JPG to PNG.pdfBe Problem Solver
 
Link your HTML Form to Google Sheet in just 3 Steps.pdf
Link your HTML Form to Google Sheet in just 3 Steps.pdfLink your HTML Form to Google Sheet in just 3 Steps.pdf
Link your HTML Form to Google Sheet in just 3 Steps.pdfBe Problem Solver
 
Submit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdfSubmit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdfBe Problem Solver
 
Learn how to use API with 2 API examples.pdf
Learn how to use API with 2 API examples.pdfLearn how to use API with 2 API examples.pdf
Learn how to use API with 2 API examples.pdfBe Problem Solver
 
6 Methods to use page scroll animation.pdf
6 Methods to use page scroll animation.pdf6 Methods to use page scroll animation.pdf
6 Methods to use page scroll animation.pdfBe Problem Solver
 
User Login in PHP with Session & MySQL.pdf
User Login in PHP with Session & MySQL.pdfUser Login in PHP with Session & MySQL.pdf
User Login in PHP with Session & MySQL.pdfBe Problem Solver
 

More from Be Problem Solver (7)

Learn to build a CodeIgniter Login and Registration with source code.pdf
Learn to build a CodeIgniter Login and Registration with source code.pdfLearn to build a CodeIgniter Login and Registration with source code.pdf
Learn to build a CodeIgniter Login and Registration with source code.pdf
 
Image Converter script for PNG to JPG & JPG to PNG.pdf
Image Converter script for PNG to JPG & JPG to PNG.pdfImage Converter script for PNG to JPG & JPG to PNG.pdf
Image Converter script for PNG to JPG & JPG to PNG.pdf
 
Link your HTML Form to Google Sheet in just 3 Steps.pdf
Link your HTML Form to Google Sheet in just 3 Steps.pdfLink your HTML Form to Google Sheet in just 3 Steps.pdf
Link your HTML Form to Google Sheet in just 3 Steps.pdf
 
Submit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdfSubmit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdf
 
Learn how to use API with 2 API examples.pdf
Learn how to use API with 2 API examples.pdfLearn how to use API with 2 API examples.pdf
Learn how to use API with 2 API examples.pdf
 
6 Methods to use page scroll animation.pdf
6 Methods to use page scroll animation.pdf6 Methods to use page scroll animation.pdf
6 Methods to use page scroll animation.pdf
 
User Login in PHP with Session & MySQL.pdf
User Login in PHP with Session & MySQL.pdfUser Login in PHP with Session & MySQL.pdf
User Login in PHP with Session & MySQL.pdf
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 

Recently uploaded (20)

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 

How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf

  • 1. How to develop an API with PHP, JSON, and POSTMAN in 9 Steps by Pawan Table of Contents ● Introduction ● What is an API? ● Why should you develop an API with PHP? ● What is JSON? ● What is POSTMAN? ● The process to develop an API ○ Establish Database ○ Provide Data in Database ○ Connect Database with PHP
  • 2. ○ Build API – GET Request ○ Test API with POSTMAN ○ Create API – GET Single data ○ Develop an API – POST Request for Insert & Update ○ Build API – DELETE Request ○ Search API – GET Request ● Conclusion Introduction Do you want to develop an API with PHP, JSON, and POSTMAN? Or are you simply looking for a way to build API for your Android App or IOS app? Look no further! In this tutorial, I will show you how to do just that! We’ll go over the basics of each technology, we are using. Then dive into how to use them together to create API for your need. By the end of this tutorial, you’ll be able to create your API with PHP and JSON. Before diving in, might I recommend a fantastic free editor that I love to use? Check out this post for more details. What is an API? So you want to build API or maybe multiple APIs?
  • 3. First, let’s understand what is an API and why we rely on them in modern web app development. The official definition you will find is: API stands for Application Programming Interface. What does that mean? In simple words, without techy jargon, an API is a piece of code you write, that allows two different pieces of software to communicate with each other. API is just a way to allow two different software to connect. Why use API though? Simple. Have you ever used an android app where you are fetching and sending data most likely you have. Then you have already used an API. Yeah! API is everywhere on the internet! With an API you connect databases like MySQL or MongoDB (or any other) to any frontend interface as an Android app or Web app. And foremost, APIs can be incredibly fast and easy to use. Learning how API works before developing an API is crucial
  • 4. So you understand the basics of API and how it works behind the scene. Let’s jump into the technology we are going to use in our API build. Why should you develop an API with PHP? While there are many languages & frameworks for creating APIs, we are going to use PHP for this purpose. But why? Let me answer the question in detail: ● PHP-based APIs are extremely easy to deploy. You don’t need to host the API on a separate physical server like Java or C. Which reduces overall cost. ● Despite being free, PHP is very powerful and you can use it to create very complex APIs. ● Even if you haven’t ever coded a programming language, PHP is easier to understand and learn. Remember HTML and CSS are structuring/styling languages, not programming ones. So now you know why I chose PHP as the backbone of my API. Let’s look at other technology and tool we need to build API. What is JSON? If you ever worked with App Developer, as I have, you will love how much they appreciate the JSON.
  • 5. Why? I know I am very fond of why question. But it’s vital to understand the reason behind why JSON dominates the API building market. Let me explain: ● JSON, as you must know, stands for JavaScript Object Notation. ● JSON is not JavaScript. Please be careful not to confuse them. ● Yes, it looks similar to JavaScript objects but that’s because JSON shares a common codebase with ECMAScript, C++, and even C. But JSON is an independent and complete language in itself. ● It’s an ultra-lightweight data-interchange format. ● It’s language-independent, platform-independent, and most importantly, developer-friendly. The only language that comes close to competing is XML but it has its issues. ● JSON data can be written in any editor, sent over the network, and parsed by any platform. It may not seem that important in a modern environment where we have high-processing systems available. But in certain situations, JSON adaptability is a lifesaver. See how vital JSON is for our process to create API. Let’s jump to the last tool we need to get started. What is POSTMAN? Before you joke, no I am not talking about the Postman who delivers letters. Our POSTMAN is an extremely powerful and necessary tool for testing and resolving bugs with our create API in PHP process. So is it an absolute necessity? The answer would be No.
  • 6. But other ways of testing your build API process are too time-consuming and not much accurate. POSTMAN is the tool all professionals rely upon. In past, POSTMAN used to be a browser extension but now it’s a full-fledged software you can download. We only need the free version for our needs. POSTMAN is the best tool to build API and test it. The process to develop an API Now that we have acquainted with all the tools we will need. Let’s jump into the process of building API: Establish Database We build the database first. I will name my database “students“. Feel free to name your database anything. But keep a note of it as you will need it later on. Next, we create a table “studentdata” which will hold our data. To make the table and its field quickly. Run the below SQL command: CREATE TABLE `studentdata` (
  • 7. `id` int(11) NOT NULL, `name` varchar(50) NOT NULL, `age` int(5) NOT NULL, `city` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; If you don’t know how to run SQL commands in PHPMyAdmin. Read my previous article, I’ve explained there how to run SQL. Now your database has a table and looks like this: The process to build API database in phpMyAdmin. Provide Data in Database Now that we have a database and a table let us insert some data by SQL for now. Don’t worry we will create a process in PHP to insert data through our API. But that comes later.
  • 8. INSERT INTO `studentdata` (`id`, `name`, `age`, `city`) VALUES (2, 'Suresh', 26, 'Chennai'), (3, 'Abhimanyu', 19, 'Kolkata'), (4, 'Raj', 25, 'Kanpur'), (5, 'Subash', 27, 'Bhopal'), (7, 'Amir', 35, 'Imphal'); For now, we have some data in our database that we can interact with, when we build our API. Connect Database with PHP Now we connect to our database with PHP. For this purpose, I created the “connect.php” file. Note: “.php” is our extension for PHP files. <?php $conn = mysqli_connect('localhost', 'root', '', 'students'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?>
  • 9. Build API – GET Request Now we start coding with PHP. So bring your favorite code editor as I started up with mine. Let’s write the first API file that will fetch everything from our database. Filename: “api_fetch_all.php“. <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); include 'connect.php'; $sql = "select * from studentdata"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { //mysqli_fetch_all gives us the data in 2D array format. // It's second parameter decide whether its assoc array or indexed. Or maybe both $data = mysqli_fetch_all($result, MYSQLI_ASSOC); echo json_encode($data); } else {
  • 10. echo json_encode(['msg' => 'No Data!', 'status' => false]); } ?> Let me explain what we wrote and why: ● Our first line “header(‘Content-Type: application/json’)“ is telling our file that we are using the JSON data format to exchange data. Without this line of code, our API will never work. ● The next header line is simply allowing our API file to access data. Sometimes you will see developers skip this line. And sometimes that’s okay. But for the best result and to avoid any future error, we did define it. ● Now, we ran the standard PHP code to select all data from the database. Then fetched that data and stored it in our “$data” variable. ● Using the famous PHP method “json_encode()“, we convert our data into JSON format. And “echo” this JSON data. ● Lastly, we encoded an error msg and status, just in case our data failed to be obtained. If you have reached this point. Congratulations! You are halfway done with learning the basics of how to create API in PHP. We have also built our first API file so let us test it with POSTMAN. Test API with POSTMAN Testing API with POSTMAN might seem daunting at first. But no worries, I will guide you through that process. ● Open your POSTMAN app and click the “+” icon where it says “Untitled Request“.
  • 11. Open first your “Untitled Request” ● Enter your API URL in the “URL-send” and set it to “GET” ● In the lower tab choose the header section. Enter header to content-type: application/JSON. Then hit Enter button. ● If done everything, you will see the JSON response in the downward part. Now we have completed our first API. This API will fetch all data for us from the database in JSON format. Let’s continue the rest of the process of developing an API.
  • 12. Create API – GET Single data Now let’s code our API file which will fetch single data by id as reference. Filename: api_fetch_single.php <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); // This is the data which is being sent to request a single data. // Since we know this request will be in json format we must decode before passing it into our php logic // file_get_contents is reading file into a string. // "php://input" is special key which insure that we can get any format of data. Even if its raw data. // True argument of json decode makes sure that we get response in assoc array $data = json_decode(file_get_contents("php://input"), true); // we are getting our passed data in $data array. But to ensure securty we will change name of id to sid. Remember we are being requested data on basis of sid after all.
  • 13. $student_id = $data['sid']; include 'connect.php'; $sql = "select * from studentdata where id = $student_id"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { //mysqli_fetch_all gives us the data in 2D array format. // It's second parameter decide whether its assoc array or indexed. Or maybe both $data = mysqli_fetch_all($result, MYSQLI_ASSOC); echo json_encode($data); } else { echo json_encode(['msg' => 'No Data!', 'status' => false]); } ?> Unlike the previous API where we were fetching every data in the table, now we are targeting a specific one. Also, we provide code “file_get_contents” which allows our reading file into a string. And “php://input” is a special key that ensures that we can get any format of data. Even if it’s raw data.
  • 14. Similarly, we will create API files for POST and DELETE requests too. Develop an API – POST Request for Insert & Update First, let’s learn how to build a POST request API that will insert our data into the database. Filename: api_insert.php <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With'); // Since we are inserting data we pass two extra headers. // 1st allow us to set the method of insert. i.e. POST in rest api // 2nd determines which type of headers can be sent. It's a secuirty header. // 'Authorization' is set for authorizing insert data. While 'X-Requested-With' is set for passing data as json
  • 15. $data = json_decode(file_get_contents("php://input"), true); $sname = $data['sname']; $sage = $data['sage']; $scity = $data['scity']; include 'connect.php'; $sql = "insert into studentdata (name, age, city) values ('$sname', '$sage', '$scity')"; if (mysqli_query($conn, $sql)) { echo json_encode(['msg' => 'Data Inserted Successfully!', 'status' => true]); } else { echo json_encode(['msg' => 'Data Failed to be Inserted!', 'status' => false]); } ?> Next, we are up for Update Requests. Which again will be done with POST Request but with little modifications. Filename: api_update.php <?php
  • 16. header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: PUT'); header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With'); // To update is similar to insert. Except in rest api update request is done throough PUT method $data = json_decode(file_get_contents("php://input"), true); $sid = $data['sid']; $sname = $data['sname']; $sage = $data['sage']; $scity = $data['scity']; include 'connect.php'; $sql = "update studentdata set name = '$sname', age = '$sage', city = '$scity' where id = '$sid'"; if (mysqli_query($conn, $sql)) { echo json_encode(['msg' => 'Data Updated Successfully!', 'status' => true]);
  • 17. } else { echo json_encode(['msg' => 'Data Failed to be Updated!', 'status' => false]); } ?> Remember while updating, we are providing a specific id with our “update-data“. Last we have only the Delete and Search API part left. Let’s keep going. Build API – DELETE Request When writing Delete Request, we add two new headers type. ● header(‘Access-Control-Allow-Methods: DELETE’) – allow us to set our API to delete files as needed. Without it, you will run into errors. ● Next headers allow us to give more control of files to API queries. It’s recommended to add them. Filename: api_delete.php <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *');
  • 18. header('Access-Control-Allow-Methods: DELETE'); header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With'); // To delete in rest api, we use DELETE method $data = json_decode(file_get_contents("php://input"), true); $sid = $data['sid']; include 'connect.php'; $sql = "delete from studentdata where id = '$sid'"; if (mysqli_query($conn, $sql)) { echo json_encode(['msg' => 'Data Deleted Successfully!', 'status' => true]); } else { echo json_encode(['msg' => 'Data Failed to be Deleted!', 'status' => false]); } ?> Before finalizing, do test your API with POSTMAN.
  • 19. And now let’s move to the last API file of the day. It’s quite an important one though, so stay alert. Search API – GET Request Filename: api_search.php <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST'); $data = json_decode(file_get_contents("php://input"), true); $searchterm = $data['search']; include 'connect.php'; $sql = "select * from studentdata where name like '%$searchterm%'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $data = mysqli_fetch_all($result, MYSQLI_ASSOC); echo json_encode($data);
  • 20. } else { echo json_encode(['msg' => 'No Data Found to search query!', 'status' => false]); } ?> See what your search should look like in the below image: Search API with GET/POST Request Note: Search functionality in an API can be developed by either GET or POST request method. In GET method case we pass our search values to the URL. In the POST method, we use the normal JSON input. Conclusion So there you have it!
  • 21. A quick and easy guide on how to develop an API with PHP, JSON, and POSTMAN. I hope this has been helpful for you. With this detailed guide at your side, we at Be Problem Solver believe you feel more confident to develop APIs. In upcoming posts, I will show you how to use this API and other third-party APIs in projects. If you have any questions or comments, then feel free to reach out. And do check out my other post about adding jazz to your website with page scroll animations. Ta-da! Guys and Gals! Happy coding!