Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 37

REST API in PHP (Full Code)

In this lesson: Create a simple REST API in PHP with GET, POST, PUT, DELETE, JSON responses and MySQL — full code and testing steps.

What is a REST API

A REST API lets programs share data over HTTP. A client (a phone app, another site, JavaScript) sends a request to a URL, and your PHP server replies with data — almost always as JSON. Instead of returning a web page, the server returns clean data the client can use.

💡 REST maps actions to HTTP methods: GET read, POST create, PUT/PATCH update, DELETE remove.

HTTP methods

MethodActionCRUD
GETFetch dataRead
POSTAdd new dataCreate
PUT / PATCHChange dataUpdate
DELETERemove dataDelete

Using the right method for each action is what makes an API "RESTful" and easy for others to understand.

Sending JSON

<?php
  header("Content-Type: application/json");
  $data = ["name" => "Aman", "class" => 12];
  echo json_encode($data);
?>
{"name":"Aman","class":12}

The header tells the client the reply is JSON, and json_encode turns your PHP array into a JSON string. This is the core of every API response.

Reading request data

<?php
  $method = $_SERVER["REQUEST_METHOD"];   // GET, POST...
  $id = $_GET["id"] ?? null;              // ?id=5 in URL

  // for a JSON body (POST/PUT):
  $body = json_decode(file_get_contents("php://input"), true);
?>

You read the method from $_SERVER, URL parameters from $_GET, and a raw JSON body from php://input, which you decode into an array.

A simple endpoint

<?php
  header("Content-Type: application/json");
  $method = $_SERVER["REQUEST_METHOD"];

  if ($method === "GET") {
      echo json_encode(["message" => "Here is your data"]);
  } elseif ($method === "POST") {
      http_response_code(201);
      echo json_encode(["message" => "Created"]);
  } else {
      http_response_code(405);
      echo json_encode(["error" => "Method not allowed"]);
  }
?>
{"message":"Here is your data"}

This single file responds differently based on the HTTP method — the basic shape of a real API endpoint.

Status codes

Tell the client what happened with http_response_code().

<?php
  http_response_code(404);
  echo json_encode(["error" => "Not found"]);
?>

Common codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Server Error. Correct codes let clients react properly instead of guessing.

Common mistakes

  • Forgetting the JSON header. Without it, clients may not treat the reply as JSON.
  • Always returning 200. Use real status codes so errors are clear.
  • Reading a JSON body from $_POST. Raw JSON comes from php://input, not $_POST.
  • No input validation. API input is user input — validate and use prepared statements.

Summary

  • A REST API shares data over HTTP, usually as JSON.
  • Methods map to CRUD: GET, POST, PUT/PATCH, DELETE.
  • Return JSON with the header plus json_encode.
  • Read the method, $_GET, and a JSON body from php://input.
  • Set correct status codes with http_response_code().

Next, format data with PHP JSON, or secure your API with JWT authentication.

Frequently Asked Questions

What is a REST API?
A REST API is a way for programs to talk to each other over HTTP using simple rules. A client sends a request to a URL with a method (GET, POST, etc.), and the server replies with data, usually as JSON. It is how apps and websites share data.
What are the main HTTP methods in a REST API?
GET to read data, POST to create, PUT or PATCH to update, and DELETE to remove. These map naturally to CRUD operations, so a well-designed API uses the right method for each action.
How do I return JSON from PHP?
Set the header with header("Content-Type: application/json"), then echo json_encode($data). This tells the client the response is JSON and sends the data in that format.
How do I read the method and body of a request?
Use $_SERVER["REQUEST_METHOD"] for the method, $_GET for query parameters, and file_get_contents("php://input") for a raw JSON body which you then json_decode.
Why do status codes matter in an API?
Status codes tell the client what happened: 200 OK, 201 Created, 404 Not Found, 400 Bad Request, 500 Server Error. Setting the right code with http_response_code() lets clients handle responses correctly.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicJWT Authentication Your progress: 37 / 50 (74%) · Lesson 38 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free