1️⃣ RESTful API Development
🔹 What is REST API?
REST (Representational State Transfer) is a way to build APIs using HTTP methods.
🔹 HTTP Methods:
GET→ Fetch dataPOST→ Create dataPUT/PATCH→ Update dataDELETE→ Remove data
🔹 Example (Simple PHP API)
<?php
header("Content-Type: application/json");$data = [
["id" => 1, "name" => "Aditya"],
["id" => 2, "name" => "Rahul"]
];echo json_encode($data);
🔹 API Routing (Basic)
$request = $_SERVER['REQUEST_METHOD'];if ($request == 'GET') {
echo "Fetching data";
} elseif ($request == 'POST') {
echo "Creating data";
}
🔹 Best Practices:
- Use JSON format
- Proper HTTP status codes (200, 404, 500)
- Secure endpoints
- Version your API (
/api/v1/)
2️⃣ Authentication (JWT & Sessions)
🔹 Session Authentication
- Stores user data on server
- Uses cookies
session_start();$_SESSION['user'] = "Aditya";if(isset($_SESSION['user'])){
echo "Logged in as " . $_SESSION['user'];
}
🔹 JWT (JSON Web Token)
Stateless authentication (no session stored on server)
🔹 JWT Flow:
- User logs in
- Server generates token
- Client stores token
- Token sent in headers for every request
🔹 Example (Concept)
$token = base64_encode(json_encode(["user_id" => 1]));
echo $token;
🔹 Real JWT uses:
- Signature
- Secret key
- Expiry time
Libraries:
- firebase/php-jwt
3️⃣ Middleware
🔹 What is Middleware?
Middleware acts as a filter before request reaches main logic.
🔹 Use Cases:
- Authentication check
- Logging
- Rate limiting
🔹 Example
function authMiddleware() {
if(!isset($_SESSION['user'])) {
die("Unauthorized");
}
}
Usage:
authMiddleware();
echo "Protected Content";
4️⃣ Dependency Injection (DI)
🔹 What is DI?
Instead of creating objects inside a class, you pass them from outside.
❌ Without DI
class User {
public function __construct() {
$this->db = new Database();
}
}
✅ With DI
class User {
private $db; public function __construct($db) {
$this->db = $db;
}
}$db = new Database();
$user = new User($db);
🔹 Benefits:
- Easy testing
- Loose coupling
- Better code structure
🚀 Pro Tips (Important for Students & Developers)
- Use MVC framework (Laravel) for real projects
- Always validate & sanitize input
- Secure APIs with JWT + HTTPS
- Use Postman for API testing
- Follow PSR standards






