Building RESTful APIs in PHP Without a Framework

Building RESTful APIs in PHP Without a Framework

June 19, 2025

Creating RESTful APIs in plain PHP helps you understand the core concepts behind API development. This blog walks you through handling HTTP methods like GET, POST, PUT, and DELETE using native PHP. You’ll learn how to structure endpoints, return JSON responses, and connect to a MySQL database. Ideal for Happy Coders developers who want full control without relying on frameworks. A great way to build lightweight, fast, and custom API solutions from scratch.

Introduction to RESTful APIs Using Core PHP

RESTful APIs allow your PHP app to communicate with external systems, mobile apps, or frontends via HTTP requests. Happy Coders demonstrates how to build REST APIs in core PHP without any frameworks. This gives developers full control and flexibility. You’ll learn to handle GET, POST, PUT, and DELETE requests from scratch. Great for lightweight or custom projects.

Key Concepts Covered:

  • HTTP methods (GET, POST, PUT, DELETE)

  • JSON response formatting

  • URL routing logic

  • Raw PHP superglobals for input

Setting Up a Basic PHP Environment for API Development

Before writing your API, you need a proper local setup. Happy Coders recommends using XAMPP, WAMP, or MAMP for easy local development. You’ll also need to enable error reporting and use Postman to test your endpoints. Keeping your folder structure organized is crucial for scalability. A clean setup helps you build faster.

Setup Essentials:

  • Use php -S localhost:8000 for quick server

  • Enable display_errors in php.ini

  • Create folders like /api, /config, /db

  • Use Postman or cURL for testing

Creating a RESTful Routing System in Pure PHP

Since there’s no framework, you’ll manually create your API router. Happy Coders teaches how to parse the URL, match the method, and call functions accordingly. This simulates a mini-framework using just conditionals and functions. You’ll also separate files by route and functionality for clarity.

Routing Tips:

  • Parse $_SERVER['REQUEST_URI'] for routes

  • Use $_SERVER['REQUEST_METHOD'] to detect actions

  • Call functions like getUsers(), createUser()

  • Return appropriate HTTP response codes

Handling JSON Requests and Responses in PHP

APIs work best when they send and receive JSON. Happy Coders explains how to read raw JSON input using file_get_contents('php://input') and return JSON responses. This ensures smooth communication with JavaScript frontends, Flutter apps, or mobile clients.

Working with JSON:

  • Use json_encode() for responses

  • Use json_decode() for input

  • Set Content-Type: application/json header

  • Handle empty or malformed JSON gracefully

Connecting to MySQL in PHP for API Data

APIs often interact with a database to fetch or store data. Happy Coders shows how to securely connect to MySQL using mysqli or PDO. You’ll learn how to fetch, insert, update, and delete data through your API routes. This brings your REST API to life.

Database Integration Points:

  • Use mysqli_connect() or PDO for connection

  • Sanitize inputs to avoid SQL injection

  • Structure queries in separate model files

  • Return results as JSON for frontend consumption

Implementing CRUD Operations Without a Framework

A RESTful API must support Create, Read, Update, and Delete actions. Happy Coders implements full CRUD operations using core PHP. Each endpoint is mapped to its corresponding function. Learn how to test it all using Postman and see how the backend handles live data.

CRUD Methods:

  • POST /users → Create a new user

  • GET /users → Read users list

  • PUT /users/{id} → Update user info

  • DELETE /users/{id} → Remove user

 

Adding HTTP Status Codes and Error Handling

A proper REST API should return meaningful HTTP status codes like 200 OK, 400 Bad Request, or 404 Not Found. Happy Coders shows how to use http_response_code() to manage responses. Error handling makes APIs more reliable and easier to debug.

Common HTTP Codes:

  • 200 – Success

  • 201 – Resource created

  • 400 – Invalid input

  • 404 – Resource not found

  • 500 – Server error

Securing Your PHP REST API with Basic Authentication

APIs without protection are vulnerable. Happy Coders adds basic security using token-based headers or simple API keys. This prevents unauthorized access to sensitive data. While advanced OAuth can be added later, basic auth is a good starting point.

Security Basics:

  • Use Authorization headers

  • Compare incoming tokens with stored API key

  • Use HTTPS to encrypt data

  • Sanitize all incoming inputs

Organizing Your API Code for Reusability and Scalability

Good code structure ensures your API grows without becoming messy. Happy Coders recommends separating files into folders like /routes, /controllers, /models, and /config. This is a mini-MVC approach—even without Laravel or CodeIgniter.

Folder Structure Suggestions:

  • /config/db.php – DB connection

  • /routes/api.php – Route logic

  • /controllers/UserController.php – Core functions

  • /models/User.php – DB queries

Testing Your REST API in PHP Using Postman and cURL

Once the API is built, you need to test it. Happy Coders uses Postman and cURL to test endpoints, payloads, and error responses. Proper testing ensures your API behaves as expected under various conditions—success, invalid data, or missing headers.

Testing Tips:

  • Use Postman for structured testing

  • Set JSON headers: Content-Type: application/json

  • Send test payloads for all methods

  • Validate both success and failure cases