You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit a08ca46
Browse filesBrowse the repository at this point in the historyBrowse files
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.
5
5
6
6
## Features
7
7
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:`).
12
16
13
17
## 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 fora specified user ID. Requires at least one of the following fieldsin 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.
44
18
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`
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
+
}
89
29
```
90
30
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
+
```
92
50
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
+
```
94
77
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
+
}
95
94
```
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
+
}
106
120
```
107
121
122
+
---
108
123
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
+
```
110
133
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
+
---
112
135
113
-
```bash
114
-
composer run dev
136
+
## Project Structure
137
+
138
+
```
139
+
.
140
+
├── public/
141
+
│ └── index.php # Application Entry Point (Bootstrap & Routing)
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`.
159
207
160
208
## License
161
209
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
169
217
<imgalt="Star History Chart"src="https://api.star-history.com/svg?repos=FarrelAD/Basic-PHP-RESTful-API&type=date&legend=top-left" />
0 commit comments