0
0
PhpHow-ToBeginner · 4 min read

How to Create REST API in PHP: Simple Guide with Example

To create a REST API in PHP, use $_SERVER to detect HTTP methods like GET or POST, and respond with JSON using header('Content-Type: application/json'). Handle requests by reading input and sending JSON responses with echo json_encode().
📐

Syntax

A basic REST API in PHP uses the $_SERVER['REQUEST_METHOD'] to check the HTTP method (GET, POST, PUT, DELETE). You read input data from php://input for methods like POST or PUT. Use header('Content-Type: application/json') to set the response type, and echo json_encode() to send JSON data back.

  • $_SERVER['REQUEST_METHOD']: Detects HTTP method.
  • php://input: Reads raw input data.
  • header(): Sets HTTP headers.
  • json_encode(): Converts PHP arrays/objects to JSON.
php
<?php
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    header('Content-Type: application/json');
    echo json_encode(['message' => 'This is a GET request']);
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    header('Content-Type: application/json');
    echo json_encode(['received' => $input]);
} else {
    header('HTTP/1.1 405 Method Not Allowed');
    echo json_encode(['error' => 'Method not allowed']);
}
?>
Output
{"message":"This is a GET request"}
💻

Example

This example shows a simple REST API in PHP that handles GET and POST requests. It returns a JSON message for GET and echoes back posted JSON data for POST.

php
<?php
// Simple REST API example
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    echo json_encode(['status' => 'success', 'data' => 'Hello from GET request']);
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if ($input === null && json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
        exit;
    }
    echo json_encode(['status' => 'success', 'received' => $input]);
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
}
?>
Output
{"status":"success","data":"Hello from GET request"}
⚠️

Common Pitfalls

Common mistakes when creating REST APIs in PHP include:

  • Not setting the Content-Type header to application/json, causing clients to misinterpret the response.
  • Failing to read raw input correctly with file_get_contents('php://input') for POST/PUT requests.
  • Not handling unsupported HTTP methods, which should return a 405 status.
  • Ignoring JSON decoding errors, leading to unexpected behavior.
php
<?php
// Wrong way: Missing Content-Type header and no input reading
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST; // This won't work for JSON input
    echo json_encode(['data' => $data]);
}

// Right way:
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
if ($input === null && json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}
echo json_encode(['received' => $input]);
?>
📊

Quick Reference

  • Detect method: $_SERVER['REQUEST_METHOD']
  • Read JSON input: json_decode(file_get_contents('php://input'), true)
  • Set JSON header: header('Content-Type: application/json')
  • Send JSON response: echo json_encode($data)
  • Handle errors: Use http_response_code() for status codes

Key Takeaways

Use $_SERVER['REQUEST_METHOD'] to detect HTTP methods in PHP REST APIs.
Always set the Content-Type header to application/json for JSON responses.
Read raw JSON input with file_get_contents('php://input') and decode it.
Return proper HTTP status codes like 405 for unsupported methods.
Validate JSON input to avoid errors and send meaningful error messages.