Building Real ApplicationsPro· 50 min read

Building a REST API

Serve JSON instead of HTML so front-ends and mobile apps can talk to your PHP — HTTP methods, status codes, JSON encoding and a working endpoint.

What you will learn

  • Explain what a REST API and JSON are
  • Read the request method and send JSON with the right status code
  • Build a small JSON endpoint with PDO

What is a REST API?

Until now your PHP has produced HTML pages for humans. But modern front-ends (React, Angular, mobile apps) do not want HTML — they want raw data they can render themselves. A REST API is a PHP back-end that, instead of pages, returns JSON (a simple text format for data) at predictable URLs. This is one of the most in-demand back-end skills, because nearly every app today is a front-end talking to an API.

Two terms. JSON (JavaScript Object Notation) is a lightweight way to write data as text — it looks just like a PHP associative array. REST is a set of conventions: use the right HTTP method for the right action, and the right status code to report the result.

HTTP methodMeansExample
GETRead dataList all products
POSTCreate something newAdd a product
PUT / PATCHUpdate existingEdit a product
DELETERemove somethingDelete a product

And a few common status codes — the number the server sends to say how it went:

CodeMeans
200OK — success
201Created — a new record was made
404Not found
400Bad request — the client sent invalid data
500Server error

Sending JSON

Two steps turn PHP data into a JSON response: set a header telling the browser "this is JSON", then echo json_encode(...) to convert a PHP array into JSON text.

Return a PHP array as JSON
<?php
  header("Content-Type: application/json");

  $product = [
    "id" => 1,
    "name" => "Keyboard",
    "price" => 1299.00
  ];

  echo json_encode($product);
?>

header("Content-Type: application/json") tells whoever called the API to expect JSON, not HTML. json_encode($product) then takes the PHP associative array and turns it into a JSON string. That string is the entire response — no HTML at all.

Note: Output (what the client receives): {"id":1,"name":"Keyboard","price":1299} The associative array became JSON text. A React or mobile app reads this, picks out name and price, and displays them however it likes. Notice it is the same shape as the PHP array — JSON and PHP arrays map almost one-to-one.

Reading the method and routing the request

A real endpoint behaves differently depending on the HTTP method. $_SERVER["REQUEST_METHOD"] tells you which method was used, and http_response_code() sets the status the client receives.

A small REST endpoint for products
<?php
  header("Content-Type: application/json");
  $method = $_SERVER["REQUEST_METHOD"];

  if ($method === "GET") {
    $stmt = $pdo->query("SELECT * FROM products");
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

  } elseif ($method === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    $stmt = $pdo->prepare("INSERT INTO products (name, price) VALUES (?, ?)");
    $stmt->execute([$data["name"], $data["price"]]);
    http_response_code(201);   // Created
    echo json_encode(["message" => "Product created"]);

  } else {
    http_response_code(405);   // Method Not Allowed
    echo json_encode(["error" => "Method not supported"]);
  }
?>

Walk through it. We read the method into $method. On a GET, we fetch all products and json_encode the array — a JSON list comes back. On a POST, the incoming JSON body arrives as raw text from php://input, so json_decode(..., true) turns it back into a PHP array; we insert it with a prepared statement (still essential against SQL injection), set status 201 "Created", and confirm with JSON. Any other method gets a 405 error. The true in json_decode means "give me an associative array".

Note: Output for a GET request: [{"id":1,"name":"Keyboard","price":1299},{"id":2,"name":"Mouse","price":499}] Output for a POST (with a 201 status): {"message":"Product created"} The same URL serves different actions based on the HTTP method, each with the correct status code. That is REST: methods describe the action, status codes describe the result, JSON carries the data.

Watch out: Even in an API, always use prepared statements for any value from the client, and validate the incoming JSON before using it. An API is just as exposed to SQL injection and bad input as a form.

Tip: Test an API without a front-end using a tool like Postman, or the curl command in your terminal — they let you send GET/POST/DELETE requests and see the JSON that comes back.

Q. What does json_encode() do in a PHP API?

Answer: jsonencode() turns PHP data (like an associative array) into a JSON string — the format front-ends and mobile apps consume. jsondecode() does the reverse.

✍️ Practice

  1. Return a single product as JSON with the correct Content-Type header.
  2. Add GET (list) and POST (create) handling to one endpoint based on the request method.

🏠 Homework

  1. Build a JSON API for a tasks table supporting GET (list) and POST (create) with proper status codes and prepared statements.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →