# βœ… Lecture 3: Introduction to Laravel & RESTful APIs > Duration: \~3 hours\ > Level: Beginners β†’ Mid\ > Project: 🧠 *Expert Platform* (API backend only) --- ## 🌟 Lecture Goals By the end of this lecture, you will: 1. Understand what Laravel is and why it's useful for API development. 2. Understand the basics of HTTP, RESTful APIs, JSON, status codes. 3. Learn how Laravel receives, processes, and responds to API requests. 4. Create your first endpoint: `GET /ping`. 5. Test it using **Postman**, a popular API client. 6. Apply everything in the context of our project: **Expert Platform**. --- ## 🧱 1. What Is Laravel? Laravel is a powerful and modern PHP framework that makes it easier to build web applications β€” especially APIs β€” using clean, organized code. - It follows the **MVC (Model-View-Controller)** pattern. - Laravel provides tools like: - **Routing** to handle incoming URLs - **Controllers** to process logic - **Models** to interact with the database - **Migrations** to manage DB tables - **Validation**, **Authentication**, **Testing**, and more ### Why use Laravel for APIs? - Clean, consistent structure - Built-in tools for routing, requests, and responses - Excellent support for building RESTful APIs - Great community and documentation --- ## 🌐 2. Understanding HTTP & RESTful API ### 🌍 What is HTTP? HTTP (HyperText Transfer Protocol) is how the browser (or client app like Postman) talks to the server. Every request follows this structure: ``` Client β†’ HTTP Request β†’ Server β†’ HTTP Response β†’ Client ``` ### βš™οΈ What is a RESTful API? REST stands for **Representational State Transfer**. A **RESTful API**: - Uses standard HTTP methods: - `GET`: retrieve data (e.g., list experts) - `POST`: create new data (e.g., register expert) - `PUT/PATCH`: update data (e.g., update profile) - `DELETE`: remove data (e.g., delete booking) - Uses URLs (routes) to define **resources** (experts, bookings, users) - Sends/receives data in **JSON** format #### βœ… Example (from Expert Platform): | HTTP Method | URL | Description | | ----------- | --------------- | -------------------------- | | GET | /api/experts | List all experts | | POST | /api/bookings | Create a booking | | DELETE | /api/users/{id} | Delete a user (admin only) | --- ## πŸ—οΈ 3. What Is JSON? JSON stands for **JavaScript Object Notation**. It’s a way of formatting data that is: - Human-readable - Easy for systems to parse - The standard for RESTful APIs ### πŸ“Œ Example JSON: ```json { "id": 1, "name": "Dr. Sara Ahmed", "languages": ["English", "Arabic"], "services": [ { "title": "Career Coaching", "price_per_session": 50 } ] } ``` ### πŸ”‘ Key Concepts: - **Key–value pairs**: `"name": "Dr. Sara"` - **Arrays**: `["English", "Arabic"]` - **Nested objects**: `"services"` contains multiple structured records --- ## πŸ›οΈ 4. Laravel Request Lifecycle: From Browser to Controller Let’s walk through what happens when you call an API: 1. **Browser/Postman sends a request** to `http://localhost:8000/api/ping` 2. Laravel finds the route in `routes/api.php` 3. The route is linked to a **controller method** 4. The controller executes logic (e.g., return response or talk to the model) 5. The controller **returns a JSON response** to the client --- ## πŸͺ  5. Setting Up Laravel + Creating Your First Endpoint ### πŸ“¦ Step 1: Create Laravel Project ```bash composer create-project laravel/laravel expert-platform-api cd expert-platform-api ``` ### βš™οΈ Step 2: Configure SQLite ```bash touch database/database.sqlite ``` Edit `.env`: ```env DB_CONNECTION=sqlite DB_DATABASE=database/database.sqlite ``` ### πŸš€ Step 3: Serve the App ```bash php artisan serve ``` Visit: `http://127.0.0.1:8000` --- ## πŸ”„ 6. Create a Basic API Endpoint `/ping` ### πŸ—‚οΈ File: `routes/api.php` ```php use Illuminate\Support\Facades\Route; Route::get('/ping', function () { return response()->json(['message' => 'pong']); }); ``` This route: - Listens for `GET /api/ping` - Returns JSON: `{ "message": "pong" }` --- ## πŸ§‘β€πŸ’» 7. Build a Controller for Better Structure ### βœ… Step 1: Create Controller ```bash php artisan make:controller Api/PingController ``` ### 🧱 File: `app/Http/Controllers/Api/PingController.php` ```php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; class PingController extends Controller { public function index(): JsonResponse { return response()->json(['message' => 'pong']); } } ``` ### βœ… Step 2: Update Route in `routes/api.php` ```php use App\Http\Controllers\Api\PingController; Route::get('/ping', [PingController::class, 'index']); ``` --- ## 🧠 Controller Class Explained ```php class PingController extends Controller { // Method called when /ping is hit public function index(): JsonResponse { return response()->json(['message' => 'pong']); } } ``` - `index()` is a method handling GET /ping - `response()->json()` sends a JSON response - We use `JsonResponse` for type safety and clarity --- ## πŸ“† What is a Model? In Laravel, a **Model** represents a database table. You define: - The table name (optional if naming is standard) - Fields (automatically picked up) - Relationships (hasMany, belongsTo) We'll explore models in Lecture 5 when we build the `Expert` model. --- ## πŸ’ͺ 8. Testing API with Postman ### πŸ› οΈ What is Postman? Postman is a GUI tool that lets you: - Make HTTP requests - See full responses - Test APIs without writing code ### ▢️ Steps: 1. Open Postman 2. Create new request: `GET http://127.0.0.1:8000/api/ping` 3. Click **Send** 4. You should see: ```json { "message": "pong" } ``` 🧠 Postman shows: - Request headers - Response status code (e.g., 200 OK) - JSON response - Timing --- ## πŸ§‘β€πŸ« Practice Task Assignment ### ✨ **Assignment: Laravel Project Setup + Your First API Endpoint** 1. Create a fresh Laravel project using the command: ```bash composer create-project laravel/laravel expert-platform-api ``` 2. (Already done by Laravel 12), Navigate into the project folder and set up the `.env` file to use SQLite as shown earlier in the lecture. 3. Create a new controller `Api/HealthCheckController` 4. Add a method `status()` to return the following JSON: ```json { "status": "API is working", "version": "v1.0", "service": "Expert Platform" } ``` 5. Add the following route to `routes/web.php`: ```php Route::get('/status', [HealthCheckController::class, 'status']); ``` 6. Test the endpoint in Postman and take a screenshot of the response. --- ## πŸ“Œ Summary Checklist βœ… What Laravel is and why it’s powerful\ βœ… MVC: Models, Views (we don’t use), Controllers\ βœ… What RESTful API is\ βœ… What HTTP requests and responses are\ βœ… How to build and test a simple endpoint\ βœ… Practiced API structure with real Expert Platform use case