What is it?
A REST API exposes resources over HTTP with JSON responses and stateless JWT authentication.
Why does it matter?
PHP REST APIs are the backbone of mobile apps and SPAs. Building one from scratch teaches every concept.
Build a REST API with JWT auth, validation, and proper HTTP responses.
Real-World Use Cases
- 💡 Use case - Practical.
- ⚡ Performance - Critical.
- 🏢 Professional - Industry.
- 📚 Learning - Essential.
Core
PHP REST API with JWT Authentication
- Stateless auth using JWT (header.payload.signature)
- Use
Authorization: Bearer - Validate input + return proper HTTP codes
- Secure endpoints via middleware
Example
"localhost",
"iat" => time(),
"exp" => time() + 3600,
"user" => $data['username']
];
$jwt = JWT::encode($payload, $key, 'HS256');
json(["token" => $jwt]);
} else {
json(["error" => "Invalid credentials"], 401);
}
}
// protected route
if ($path == "/profile" && $method == "GET") {
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
json(["error" => "Token missing"], 401);
}
$token = str_replace("Bearer ", "", $headers['Authorization']);
try {
$decoded = JWT::decode($token, new Key($key, 'HS256'));
json(["user" => $decoded->user]);
} catch (Exception $e) {
json(["error" => "Invalid token"], 401);
}
}
// fallback
json(["error" => "Not found"], 404);
Best Practice
- Use HTTPS only
- Store secret in env variables, not code
- Set short token expiry + refresh tokens
- Validate all inputs (never trust request data)
- Use proper HTTP codes:
200OK201Created400Bad Request401Unauthorized403Forbidden
- Add rate limiting + logging
- Use frameworks (Laravel/Slim) for production
Q: What is JWT?
JWT is a signed token encoding claims. Server generates it on login; client sends it in Authorization: Bearer header. Server verifies signature — no database lookup needed.
Comments (0)
No comments yet. Be the first!
Leave a Comment