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

Page 1

How to develop anAPI with PHP, JSON, and POSTMAN in 9 Steps by Pawan Table of Contents ● Introduction ● What is anAPI? ● Why should you develop anAPI with PHP? ● What is JSON? ● What is POSTMAN? ● The process to develop anAPI ○ Establish Database ○ Provide Data in Database ○ Connect Database with PHP

○ BuildAPI GETRequest ○ TestAPI with POSTMAN ○ CreateAPI GETSingle data ○ Develop anAPI POSTRequest for Insert & Update ○ BuildAPI DELETE Request ○ SearchAPI GETRequest ● Conclusion

Or are you simply looking for a way to buildAPI for yourAndroidApp or IOS app? Look no further! In this tutorial, I will show you how to do just that!

Do you want to develop anAPI with PHP, JSON, and POSTMAN?

We’ll go over the basics of each technology, we are using.Then dive into how to use them together to createAPI for your need By the end of this tutorial, you’ll be able to create yourAPI 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 anAPI? So you want to buildAPI or maybe multipleAPIs?

Introduction

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 useAPI 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 anAPI Yeah!API is everywhere on the internet! With anAPI you connect databases like MySQLor MongoDB (or any other) to any frontend interface as anAndroid app or Web app.And foremost,APIs can be incredibly fast and easy to use Learning howAPI works before developing anAPI is crucial

First, let’s understand what is anAPI 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?

● PHP-basedAPIs are extremely easy to deploy.You don’t need to host theAPI on a separate physical server like Java or C Which reduces overall cost.

What is JSON? If you ever worked withApp Developer, as I have, you will love how much they appreciate the JSON

Why should you develop anAPI with PHP?

● Despite being free, PHPis very powerful and you can use it to create very complexAPIs.

Let me answer the question in detail:

So you understand the basics ofAPI and how it works behind the scene Let’s jump into the technology we are going to use in ourAPI build.

● Even if you haven’t ever coded a programming language, PHPis easier to understand and learn. Remember HTMLand CSS are structuring/styling languages, not programming ones. So now you know why I chose PHPas the backbone of myAPI. Let’s look at other technology and tool we need to buildAPI

While there are many languages & frameworks for creatingAPIs, we are going to use PHP for this purpose But why?

● 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.

● 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 createAPI. Let’s jump to the last tool we need to get started

Why?

I know I am very fond of why question. But it’s vital to understand the reason behind why JSON dominates theAPI building market Let me explain:

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 createAPI in PHPprocess. So is it an absolute necessity?The answer would be No.

What is POSTMAN?

● JSON is not JavaScript. Please be careful not to confuse them.

● It’s an ultra-lightweight data-interchange format.

● JSON, as you must know, stands for JavaScript Object Notation

● It’s language independent, platform independent, and most importantly, developer friendly.The only language that comes close to competing is XMLbut it has its issues

The process to develop anAPI Now that we have acquainted with all the tools we will need. Let’s jump into the process of buildingAPI: Establish Database

POSTMAN is the best tool to buildAPI and test it.

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 SQLcommand: CREATE TABLE `studentdata` (

But other ways of testing your buildAPI 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.

by SQL for now Don’t worry we will create

let us insert

Provide Data in Database

and

in PHPto insert data through our API. But that comes later.

Now that we have a database a table some data a process

`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 SQLcommands 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 buildAPI database in phpMyAdmin.

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 ourAPI 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 PHPfiles. <?php $conn = mysqli connect('localhost', 'root', '' , 'students'); if (!$conn) { die("Connection failed: " . mysqli connect error()); } ?>

BuildAPI – GETRequest Now we start coding with PHP. So bring your favorite code editor as I started up with mine Let’s write the firstAPI 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 {

● Open your POSTMAN app and click the “+” icon where it says “Untitled Request“ .

● Now, we ran the standard PHPcode to select all data from the database.Then fetched that data and stored it in our “$data” variable

● 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 createAPI in PHP We have also built our firstAPI file so let us test it with POSTMAN.

● The next header line is simply allowing ourAPI 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

Let me explain what we wrote and why:

● Using the famous PHPmethod “json encode()“ , we convert our data into JSON format And “echo” this JSON data

TestAPI with POSTMAN TestingAPI with POSTMAN might seem daunting at first. But no worries, I will guide you through that process.

echo json encode(['msg' => 'No Data!', 'status' => false]); } ?>

● 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, ourAPI will never work.

Open first your “Untitled Request”

● 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 firstAPI ThisAPI will fetch all data for us from the database in JSON format. Let’s continue the rest of the process of developing anAPI

● Enter yourAPI URLin the “URL-send” and set it to “GET”

CreateAPI – GETSingle data Now let’s code ourAPI 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 previousAPI 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 createAPI files for POSTand DELETE requests too Develop anAPI – POSTRequest for Insert & Update First, let’s learn how to build a POSTrequestAPI 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 SearchAPI part left. Let’s keep going. BuildAPI – DELETE Request When writing Delete Request, we add two new headers type. ● header(‘Access Control Allow Methods: DELETE’) allow us to set ourAPI to delete files as needed. Without it, you will run into errors ● Next headers allow us to give more control of files toAPI 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 yourAPI with POSTMAN.

And now let’s move to the lastAPI file of the day It’s quite an important one though, so stay alert. SearchAPI – GETRequest 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: SearchAPI with GET/POSTRequest Note: Search functionality in anAPI 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!

Aquick and easy guide on how to develop anAPI 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 thisAPI 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!

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.