PHP : REST API – Introduction

An API (Application Programming Interface) lets two software systems talk to each other. A REST API does this over the internet using normal HTTP requests, and it usually sends and receives data in JSON format. In this tutorial you will learn how PHP can read data from an API, and how it can create, update and delete data using an API.


Why do we use APIs?

  • A weather app gets live weather data from a weather service.
  • A website shows payments through a payment gateway, like Razorpay or PayPal.
  • The same data is used by a website and by a mobile app, both call the same API.
  • A website shows your social media posts, by reading them from the API of that platform.

What is REST?

REST (REpresentational State Transfer) is a style for building web services. Every thing (like a user or a post) has its own URL, called an endpoint, and the HTTP method tells what to do with it.

HTTP methodUseExample
GETRead dataGET /users/1 gets the user with id 1
POSTCreate new dataPOST /users creates a new user
PUTReplace or update dataPUT /users/1 updates the user 1
PATCHUpdate only some fieldsPATCH /users/1
DELETERemove dataDELETE /users/1 deletes the user 1

Common HTTP status codes

CodeMeaning
200OK, the request worked
201Created, a new record was made
204Success, with no content to return
400Bad request, your data is wrong
401 / 403Not logged in / not allowed
404Not found
500Server error

What is JSON?

JSON (JavaScript Object Notation) is the most used format to send data between applications. Objects are written in curly brackets { } and lists in square brackets [ ].

{
    "id": 1,
    "name": "Robin",
    "skills": ["PHP", "MySQL"]
}

PHP has two functions for JSON: json_decode() turns JSON text into a PHP array or object, and json_encode() does the opposite.

<?php
$json = '{"id":1,"name":"Robin","skills":["PHP","MySQL"]}';

$data = json_decode($json, true);   // true = give an array
echo $data["name"] . " knows " . $data["skills"][0] . "<br>";

echo json_encode(["id" => 1, "name" => "Robin"]);
?>

Output:

Tutorials Class - Output Window

Robin knows PHP
{“id”:1,”name”:”Robin”}


Ways to call an API from PHP

MethodWhen to useChapter
file_get_contents()Simple GET requestsfile_get_contents()
cURLFull control: all methods, headers, errorsGET, POST, PUT, DELETE
Guzzle libraryBig projects (installed with Composer)Not covered here

Practice API used in this tutorial

To practice we use JSONPlaceholder, a free fake API for testing, at https://jsonplaceholder.typicode.com. It has endpoints like /users and /posts. It accepts POST, PUT and DELETE requests and gives a correct response, but it does not really save any change, so you can test without any risk. If the site is not available in future, you can use any other test API with the same code idea.

Note: For real APIs you usually need an API key or a token. Send it in a header, keep it outside the public folder, and use only HTTPS. Never write a secret key inside a page that visitors can open.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.