Skip to content

Commit a08ca46

Browse files
committed
refactor: modernize API architecture, apply PSR-4/12 standards, and add PHPUnit test suite
1 parent 2b545fb commit a08ca46

22 files changed

Lines changed: 2638 additions & 558 deletions

‎.env.example‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
DB_HOST=localhost
2+
DB_USER=root
3+
DB_PASS=
4+
DB_NAME=db_php_restful_api
5+
DB_PORT=3306

‎.gitignore‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
vendor/
22
.env
3-
logs/
3+
logs/
4+
5+
# testing tools
6+
.phpunit.cache

‎README.md‎

Lines changed: 175 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -1,161 +1,209 @@
11
# Basic RESTful API in PHP
22

33
## Overview
4-
This project is a simple RESTful API built in native PHP. It serves as a learning resource for those interested in understanding how to create a basic RESTful API from scratch. The API provides endpoints to manage user data, allowing users to perform CRUD (Create, Read, Update, Delete) operations.
4+
This project is a RESTful API built in native PHP following modern PHP standards (PSR-4 autoloading with PascalCase namespace directories, PSR-12 coding standard, strict types, pure JSON REST conventions, and automated PHPUnit testing). It provides endpoints to manage user data, allowing clients to perform full CRUD (Create, Read, Update, Delete) operations using clean JSON payloads.
55

66
## Features
77

8-
- Fully implemented in native PHP with minimal dependencies.
9-
- Basic CRUD operations for user data.
10-
- Clean and organized code structure.
11-
- Custom error handling and responses.
8+
- **Standard PSR-4 Autoloading**: All application source code is consolidated inside `src/` under the `App\` namespace matching directory casing (`App\Config\`, `App\Controllers\`, `App\Models\`, `App\Routes\`, `App\Utils\`).
9+
- **Reusable Utility Layer (`App\Utils`)**:
10+
- `Response::json()`: Standardized HTTP status codes, headers, and JSON encoding.
11+
- `Request::getJson()`: Secure JSON request parsing with fallback and mock testing support.
12+
- `Logger::error()`: Centralized error logging with absolute project path resolution.
13+
- **Pure RESTful Architecture**: All requests and responses communicate using standard `application/json`.
14+
- **Type Safety**: Enforces `declare(strict_types=1);` and scalar typing throughout models and controllers.
15+
- **Automated Testing**: Comprehensive PHPUnit test suite covering utilities, database configuration, and model CRUD operations using in-memory SQLite (`:memory:`).
1216

1317
## API Endpoints
14-
Here are the available API endpoints:
15-
- Get All Users
16-
```bash
17-
GET /api/users
18-
```
19-
Retrieves a list of all users
20-
21-
- Add New User
22-
```bash
23-
POST /api/users
24-
```
25-
Adds a new user to the database. Requires name, age, and job in the request body.
26-
27-
- Get User by ID
28-
```bash
29-
GET /api/users/:id
30-
```
31-
Retrieves user data for a specified user ID.
32-
33-
- Update User Data
34-
```bash
35-
PATCH /api/users/:id
36-
```
37-
Updates user data for a specified user ID. Requires at least one of the following fields in the request body: **name**, **age**, or **job**.
38-
39-
- Delete User by ID
40-
```bash
41-
DELETE /api/users/:id
42-
```
43-
Deletes the user with the specified user ID.
4418

45-
## Project Structure
46-
47-
The main components of the project include:
48-
- **public**: Contains `index.php` file as entry point for the project
49-
- **config**: Contains configuration files and environment variables.
50-
- **src/routes**: Contains route for HTTP request
51-
- **src/controllers**: Contains logic for handling API requests. Example: `UsersController.php`
52-
- **src/models**: Contains database interaction logic. Example: `User.php`
53-
54-
## Getting Started
55-
56-
To get started with this project, follow the steps below.
19+
All request and response bodies use JSON (`Content-Type: application/json`).
5720

58-
### Prerequisites
59-
- PHP 7.4 or higher
60-
- A web server (e.g., Apache, Nginx, or PHP built in web server)
61-
- Composer (for dependency management)
62-
63-
### Installation
64-
1. Clone the repository:
65-
```
66-
git clone https://github.com/FarrelAD/Basic-PHP-RESTful-API.git
67-
```
68-
2. Navigate to the project directory:
69-
```bash
70-
cd Basic-PHP-RESTful-API
71-
```
72-
3. Install the dependencies:
73-
```bash
74-
composer install
75-
```
76-
77-
### Configuration
78-
79-
#### Environment file
80-
81-
Create a **.env** file in the project root directory to store your environment variables. This is essential for configuring database connections and other settings.
82-
83-
Example .env file:
84-
```env
85-
DB_HOST=localhost
86-
DB_USER=root
87-
DB_PASS=my_password
88-
DB_NAME=db_php_restful_api
21+
### 1. Root / Welcome
22+
- **Method**: `GET /`
23+
- **Response**: `200 OK`
24+
```json
25+
{
26+
"status": "success",
27+
"message": "Welcome to Basic PHP RESTful API"
28+
}
8929
```
9030

91-
#### Error Log
31+
---
32+
33+
### 2. Get All Users
34+
- **Method**: `GET /api/users`
35+
- **Response**: `200 OK`
36+
```json
37+
{
38+
"status": "success",
39+
"message": "Successfully retrieved all users",
40+
"data": [
41+
{
42+
"id": 1,
43+
"name": "John Doe",
44+
"age": 30,
45+
"job": "Software Engineer"
46+
}
47+
]
48+
}
49+
```
9250

93-
Create an **error.log** file in the logs directory to store all error logs that occur when the application runs.
51+
---
52+
53+
### 3. Create User
54+
- **Method**: `POST /api/users`
55+
- **Headers**: `Content-Type: application/json`
56+
- **Request Body**:
57+
```json
58+
{
59+
"name": "Alice Smith",
60+
"age": 28,
61+
"job": "Backend Developer"
62+
}
63+
```
64+
- **Response**: `201 Created`
65+
```json
66+
{
67+
"status": "success",
68+
"message": "Successfully created user",
69+
"data": {
70+
"id": 2,
71+
"name": "Alice Smith",
72+
"age": 28,
73+
"job": "Backend Developer"
74+
}
75+
}
76+
```
9477

78+
---
79+
80+
### 4. Get User by ID
81+
- **Method**: `GET /api/users/:id`
82+
- **Response**: `200 OK`
83+
```json
84+
{
85+
"status": "success",
86+
"message": "Successfully retrieved user",
87+
"data": {
88+
"id": 1,
89+
"name": "John Doe",
90+
"age": 30,
91+
"job": "Software Engineer"
92+
}
93+
}
9594
```
96-
(root)
97-
├───config
98-
├───logs
99-
│ └───error.log # This is new file to log the error
100-
├───public
101-
├───src
102-
│ ├───controllers
103-
│ ├───models
104-
│ └───routes
105-
└───vendor
95+
- **Error Response**: `404 Not Found` if user does not exist.
96+
97+
---
98+
99+
### 5. Update User Data
100+
- **Method**: `PATCH /api/users/:id`
101+
- **Headers**: `Content-Type: application/json`
102+
- **Request Body** (provide any combination of `name`, `age`, or `job`):
103+
```json
104+
{
105+
"job": "Lead Architect"
106+
}
107+
```
108+
- **Response**: `200 OK`
109+
```json
110+
{
111+
"status": "success",
112+
"message": "Successfully updated user",
113+
"data": {
114+
"id": 1,
115+
"name": "John Doe",
116+
"age": 30,
117+
"job": "Lead Architect"
118+
}
119+
}
106120
```
107121

122+
---
108123

109-
## Usage
124+
### 6. Delete User by ID
125+
- **Method**: `DELETE /api/users/:id`
126+
- **Response**: `200 OK`
127+
```json
128+
{
129+
"status": "success",
130+
"message": "Successfully deleted user"
131+
}
132+
```
110133

111-
After setting up the project, you can start the web server first. You can use Apache HTTPD, NGINX or PHP built in web server.
134+
---
112135

113-
```bash
114-
composer run dev
136+
## Project Structure
137+
138+
```
139+
.
140+
├── public/
141+
│ └── index.php # Application Entry Point (Bootstrap & Routing)
142+
├── src/
143+
│ ├── Config/
144+
│ │ └── Database.php # App\Config\Database - PDO Connection Management
145+
│ ├── Controllers/
146+
│ │ └── UsersController.php # App\Controllers\UsersController - Request Handling
147+
│ ├── Models/
148+
│ │ └── User.php # App\Models\User - Database CRUD Operations
149+
│ ├── Routes/
150+
│ │ └── api.php # Route Matching & HTTP Method Dispatcher
151+
│ └── Utils/
152+
│ ├── Logger.php # App\Utils\Logger - Centralized Error Logging
153+
│ ├── Request.php # App\Utils\Request - JSON Body Parser
154+
│ └── Response.php # App\Utils\Response - Standardized JSON Emitter
155+
├── tests/
156+
│ └── Unit/
157+
│ ├── DatabaseTest.php # Database configuration unit tests
158+
│ ├── RequestTest.php # Request parsing unit tests
159+
│ ├── ResponseTest.php # Response emitter unit tests
160+
│ └── UserTest.php # User model in-memory SQLite unit tests
161+
├── .env.example # Environment variables template
162+
├── composer.json # PSR-4 Autoload mappings & PHPUnit dependencies
163+
├── phpunit.xml # PHPUnit test suite configuration
164+
└── README.md
115165
```
116166

117-
After that, you can access the API endpoints using a tool like Postman or cURL.Below are some examples of how to use the endpoints:
167+
---
118168

119-
### Get All Users
120-
```bash
121-
curl -X GET http://localhost:8000/api/users
122-
```
169+
## Getting Started
123170

124-
### Add New User
125-
```bash
126-
curl -X POST http://localhost:8000/api/users -d "name=John Doe&age=30&job=Developer"
127-
```
171+
### Prerequisites
172+
- PHP 7.4 or higher (PHP 8.x recommended)
173+
- MySQL / MariaDB database
174+
- Composer
128175

129-
### Get User By ID
176+
### Installation
177+
1. Clone the repository:
178+
```bash
179+
git clone https://github.com/FarrelAD/Basic-PHP-RESTful-API.git
180+
cd Basic-PHP-RESTful-API
181+
```
182+
2. Install dependencies:
183+
```bash
184+
composer install
185+
```
186+
3. Copy environment configuration:
187+
```bash
188+
cp .env.example .env
189+
```
190+
Configure your database credentials in `.env`.
191+
192+
### Running Tests
193+
Execute unit tests using Composer:
130194
```bash
131-
curl -X GET http://localhost:8000/api/users/1
132-
195+
composer test
133196
```
134-
135-
### Update User Data
197+
Or directly with PHPUnit:
136198
```bash
137-
curl -X PATCH http://localhost:8000/api/users/1 -d '{"name": "Jane Doe"}'
199+
vendor/bin/phpunit
138200
```
139201

140-
### Delete User By ID
202+
### Running the Development Server
141203
```bash
142-
curl -X DELETE http://localhost:8000/api/users/1
204+
composer dev
143205
```
144-
145-
## Error Handling
146-
147-
### API Response Code
148-
The API includes custom error handling to manage different scenarios, such as:
149-
150-
- 404 Not Found: When a user is not found.
151-
- 400 Bad Request: When the request body is empty or required data is missing.
152-
- 500 Internal Server Error: For unexpected errors during processing.
153-
154-
All responses are returned in JSON format, providing a consistent structure for success and error messages.
155-
156-
### Error Log
157-
All server errors are logged to a file located at **logs/error.log**. This log file can be used to monitor your web application when it is live in production, helping to identify and troubleshoot issues effectively.
158-
206+
The API will be available at `http://localhost:8000`.
159207

160208
## License
161209
This project is open-source and available under the MIT License. Feel free to modify and use it as a learning resource.
@@ -169,3 +217,4 @@ This project is open-source and available under the MIT License. Feel free to mo
169217
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=FarrelAD/Basic-PHP-RESTful-API&type=date&legend=top-left" />
170218
</picture>
171219
</a>
220+

‎composer.json‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,27 @@
11
{
2+
"name": "farrelad/basic-php-restful-api",
3+
"description": "Basic RESTful API in PHP",
4+
"type": "project",
5+
"license": "MIT",
6+
"autoload": {
7+
"psr-4": {
8+
"App\\": "src/"
9+
}
10+
},
11+
"autoload-dev": {
12+
"psr-4": {
13+
"Tests\\": "tests/"
14+
}
15+
},
216
"scripts": {
3-
"dev": "php -S localhost:8000 -t public"
17+
"dev": "php -S localhost:8000 -t public",
18+
"test": "phpunit"
419
},
520
"require": {
21+
"php": ">=7.4",
622
"vlucas/phpdotenv": "^5.6"
23+
},
24+
"require-dev": {
25+
"phpunit/phpunit": "10.5"
726
}
827
}

0 commit comments

Comments
 (0)