PHP REST APIs

πŸ“˜ PHP πŸ‘ 28 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

What is a REST API?

A REST API (Representational State Transfer Application Programming Interface) allows different applications to communicate with each other using HTTP methods. In PHP, REST APIs are commonly used for mobile apps, frontend frameworks (React, Vue), and third-party integrations.


Key Principles of REST

  • Client–Server architecture

  • Stateless communication

  • Uses standard HTTP methods

  • Resource-based URLs

  • JSON is the most common response format


Common HTTP Methods

MethodPurpose
GETRetrieve data
POSTCreate new data
PUTUpdate existing data
PATCHPartially update data
DELETEDelete data

REST API Response Format (JSON)

{ "status": true, "message": "Data fetched successfully", "data": [] }

Basic PHP REST API Setup

Set Headers

header("Content-Type: application/json"); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");

Handling HTTP Request Method

$method = $_SERVER['REQUEST_METHOD'];

GET Request Example

if ($method === 'GET') { echo json_encode([ "status" => true, "message" => "GET request successful" ]); }

POST Request Example

if ($method === 'POST') { $data = json_decode(file_get_contents("php://input"), true); echo json_encode([ "status" => true, "data" => $data ]); }

CRUD Example with PHP REST API

Read (GET)

$stmt = $pdo->query("SELECT * FROM users"); $data = $stmt->fetchAll(); echo json_encode($data);

Create (POST)

$data = json_decode(file_get_contents("php://input"), true); $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->execute([$data['name'], $data['email']]);

Update (PUT)

$data = json_decode(file_get_contents("php://input"), true); $stmt = $pdo->prepare("UPDATE users SET name=? WHERE id=?"); $stmt->execute([$data['name'], $data['id']]);

Delete (DELETE)

parse_str(file_get_contents("php://input"), $data); $stmt = $pdo->prepare("DELETE FROM users WHERE id=?"); $stmt->execute([$data['id']]);

API Routing (Simple Example)

$endpoint = $_GET['endpoint'] ?? ''; if ($endpoint === 'users') { // handle users API }

API Authentication (Basic Token Example)

$headers = getallheaders(); if ($headers['Authorization'] !== 'Bearer mytoken') { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); exit; }

HTTP Status Codes

CodeMeaning
200OK
201Created
400Bad Request
401Unauthorized
404Not Found
500Server Error

Error Handling in REST APIs

http_response_code(400); echo json_encode(["error" => "Invalid request"]);

Best Practices for PHP REST APIs

  • Use meaningful endpoints (/api/users)

  • Always return JSON

  • Use proper HTTP status codes

  • Validate input data

  • Secure APIs using tokens/JWT

  • Version your APIs (/api/v1/)


Common Use Cases

  • Mobile app backend

  • SPA frontend (React, Angular)

  • Microservices

  • Third-party integrations


Conclusion

PHP REST APIs provide a powerful way to build scalable, platform-independent services. Understanding REST principles and secure API development is essential for modern backend development.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes