๐ŸŒ Week 18, Day 1: REST API Introduction & Concepts

Learn RESTful Architecture and Build Your First API

๐Ÿ“– Learning Objectives

๐ŸŽฏ What is REST API?

REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API allows different applications to communicate with each other over HTTP using standard methods.

Key Characteristics of REST:

Why Use REST APIs?

REST vs Traditional Web Apps:

Traditional Web App REST API
Returns HTML pages Returns JSON/XML data
Server-side rendering Client-side rendering
Uses Blade templates Returns raw data
Browser-specific Platform-independent
Session-based Token-based (stateless)

๐Ÿ”ง HTTP Methods (CRUD Operations)

REST APIs use standard HTTP methods to perform operations on resources. These methods correspond to CRUD (Create, Read, Update, Delete) operations.

HTTP Method CRUD Operation Description Example
GET Read Retrieve data (does not modify) GET /api/posts - Get all posts
GET /api/posts/1 - Get post #1
POST Create Create new resource POST /api/posts - Create new post
PUT Update Replace entire resource PUT /api/posts/1 - Replace post #1
PATCH Update Partially update resource PATCH /api/posts/1 - Update some fields
DELETE Delete Remove resource DELETE /api/posts/1 - Delete post #1

HTTP Methods Characteristics:

Method Safe Idempotent Has Body
GET Yes Yes No
POST No No Yes
PUT No Yes Yes
PATCH No No Yes
DELETE No Yes No
๐Ÿ’ก Tip: Safe means the method doesn't modify data. Idempotent means calling it multiple times has the same effect as calling it once.

๐Ÿ“„ JSON Format and Responses

JSON (JavaScript Object Notation) is the standard data format for REST APIs. It's lightweight, human-readable, and supported by all programming languages.

JSON Structure Examples:

1. Single Resource (Object):

{ "id": 1, "title": "Introduction to REST APIs", "content": "REST APIs are awesome...", "author": "John Doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" }

2. Collection of Resources (Array):

{ "data": [ { "id": 1, "title": "First Post", "author": "John" }, { "id": 2, "title": "Second Post", "author": "Jane" } ], "total": 2, "page": 1 }

3. Success Response:

{ "success": true, "message": "Post created successfully", "data": { "id": 3, "title": "New Post" } }

4. Error Response:

{ "success": false, "message": "Validation failed", "errors": { "title": ["The title field is required"], "content": ["The content must be at least 10 characters"] } }

JSON Data Types:

๐Ÿš€ HTTP Status Codes

HTTP status codes indicate the result of an API request. They help clients understand what happened without parsing the response body.

Common Status Codes:

Code Category Description Usage
200 Success OK Successful GET, PUT, PATCH request
201 Success Created Resource successfully created (POST)
204 Success No Content Successful DELETE (no response body)
400 Client Error Bad Request Invalid request data/validation error
401 Client Error Unauthorized Authentication required
403 Client Error Forbidden Not authorized to access resource
404 Client Error Not Found Resource doesn't exist
422 Client Error Unprocessable Entity Validation errors
500 Server Error Internal Server Error Server crashed or exception occurred

Status Code Categories:

๐Ÿ›ฃ๏ธ Setting Up API Routes in Laravel

Laravel provides a separate routes/api.php file for API routes. All routes in this file are automatically prefixed with /api.

Difference Between web.php and api.php:

routes/web.php routes/api.php
For traditional web pages For API endpoints
Returns HTML views Returns JSON data
Uses sessions and cookies Stateless (uses tokens)
CSRF protection enabled CSRF protection disabled
URL: /posts URL: /api/posts

Basic API Routes (routes/api.php):

<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; // Simple GET route - returns JSON Route::get('/hello', function () { return ['message' => 'Hello, World!']; }); // GET route with parameter Route::get('/users/{id}', function ($id) { return [ 'id' => $id, 'name' => 'John Doe', 'email' => 'john@example.com' ]; }); // POST route - receives data Route::post('/posts', function (Request $request) { return [ 'success' => true, 'message' => 'Post created', 'data' => $request->all() ]; });

RESTful Resource Routes:

// Individual routes Route::get('/posts', [PostController::class, 'index']); // List all Route::post('/posts', [PostController::class, 'store']); // Create new Route::get('/posts/{id}', [PostController::class, 'show']); // Show one Route::put('/posts/{id}', [PostController::class, 'update']); // Update Route::delete('/posts/{id}', [PostController::class, 'destroy']); // Delete // OR use resource route (creates all routes above) Route::apiResource('posts', PostController::class);
๐Ÿ’ก Tip: Use php artisan route:list to see all registered routes including API routes.

๐Ÿ’ป Creating Your First API Endpoints

Step 1: Create a Simple GET Endpoint

Edit routes/api.php:

<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; // Test endpoint Route::get('/test', function () { return [ 'status' => 'success', 'message' => 'API is working!', 'timestamp' => now() ]; }); // Get all students Route::get('/students', function () { return [ 'data' => [ ['id' => 1, 'name' => 'Alice', 'grade' => 'A'], ['id' => 2, 'name' => 'Bob', 'grade' => 'B'], ['id' => 3, 'name' => 'Charlie', 'grade' => 'A'] ], 'total' => 3 ]; }); // Get single student by ID Route::get('/students/{id}', function ($id) { $students = [ 1 => ['id' => 1, 'name' => 'Alice', 'grade' => 'A', 'email' => 'alice@example.com'], 2 => ['id' => 2, 'name' => 'Bob', 'grade' => 'B', 'email' => 'bob@example.com'], 3 => ['id' => 3, 'name' => 'Charlie', 'grade' => 'A', 'email' => 'charlie@example.com'] ]; if (isset($students[$id])) { return $students[$id]; } return response()->json([ 'error' => 'Student not found' ], 404); });

Step 2: Create a POST Endpoint

// Create new student Route::post('/students', function (Request $request) { // Validate incoming data $validated = $request->validate([ 'name' => 'required|string|max:255', 'grade' => 'required|string|max:2', 'email' => 'required|email' ]); // In real app, save to database // For now, just return the data with fake ID return response()->json([ 'success' => true, 'message' => 'Student created successfully', 'data' => [ 'id' => rand(4, 100), 'name' => $validated['name'], 'grade' => $validated['grade'], 'email' => $validated['email'], 'created_at' => now() ] ], 201); // 201 = Created });

Step 3: Return Proper Status Codes

// Success with 200 OK return response()->json($data, 200); // Created with 201 Created return response()->json($data, 201); // Not found with 404 return response()->json(['error' => 'Not found'], 404); // Validation error with 422 return response()->json(['errors' => $errors], 422); // Server error with 500 return response()->json(['error' => 'Server error'], 500);

๐Ÿงช Testing APIs with Postman

Postman is a popular tool for testing APIs. It allows you to send HTTP requests and view responses without writing any code.

Installing Postman:

  1. Go to https://www.postman.com/downloads/
  2. Download Postman for Windows
  3. Install and create a free account (optional)
  4. Launch Postman

Testing GET Request:

  1. Open Postman
  2. Click "New" โ†’ "HTTP Request"
  3. Set method to GET
  4. Enter URL: http://localhost:8000/api/students
  5. Click "Send"
  6. View the JSON response below

Testing POST Request:

  1. Create new request
  2. Set method to POST
  3. Enter URL: http://localhost:8000/api/students
  4. Click "Body" tab
  5. Select "raw" and choose "JSON" from dropdown
  6. Enter JSON data:
    { "name": "David", "grade": "A", "email": "david@example.com" }
  7. Click "Send"
  8. You should see 201 Created status and response data

Alternative Tools:

๐Ÿ’ก Tip: For GET requests, you can test directly in browser: http://localhost:8000/api/students

๐ŸŒ API URL Structure and Conventions

RESTful URL Patterns:

Action HTTP Method URL Pattern Example
List all GET /api/resources GET /api/posts
Get one GET /api/resources/{id} GET /api/posts/5
Create POST /api/resources POST /api/posts
Update PUT/PATCH /api/resources/{id} PUT /api/posts/5
Delete DELETE /api/resources/{id} DELETE /api/posts/5

URL Naming Best Practices:

Query Parameters Examples:

// Pagination GET /api/posts?page=2&per_page=10 // Filtering GET /api/posts?status=published&category=laravel // Sorting GET /api/posts?sort_by=created_at&order=desc // Searching GET /api/posts?search=rest+api // Multiple filters GET /api/posts?author=john&status=published&sort=latest

๐Ÿ”จ Complete Working Example

Full API Routes (routes/api.php):

<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; // In-memory data store (array) $books = [ ['id' => 1, 'title' => 'Laravel Basics', 'author' => 'John Doe', 'price' => 29.99], ['id' => 2, 'title' => 'REST API Guide', 'author' => 'Jane Smith', 'price' => 34.99], ['id' => 3, 'title' => 'PHP Mastery', 'author' => 'Bob Johnson', 'price' => 39.99], ]; // GET /api/books - List all books Route::get('/books', function () use ($books) { return response()->json([ 'success' => true, 'data' => $books, 'total' => count($books) ], 200); }); // GET /api/books/{id} - Get single book Route::get('/books/{id}', function ($id) use ($books) { foreach ($books as $book) { if ($book['id'] == $id) { return response()->json([ 'success' => true, 'data' => $book ], 200); } } return response()->json([ 'success' => false, 'message' => 'Book not found' ], 404); }); // POST /api/books - Create new book Route::post('/books', function (Request $request) { // Validate request data $validated = $request->validate([ 'title' => 'required|string|max:255', 'author' => 'required|string|max:255', 'price' => 'required|numeric|min:0' ]); // Create new book (in real app, save to database) $newBook = [ 'id' => rand(4, 1000), 'title' => $validated['title'], 'author' => $validated['author'], 'price' => $validated['price'], 'created_at' => now()->toDateTimeString() ]; return response()->json([ 'success' => true, 'message' => 'Book created successfully', 'data' => $newBook ], 201); });
๐Ÿ’ก Tip: This example uses an array for simplicity. In real applications, you'll use database models (covered in next lessons).

โœ๏ธ Practice Exercises

Exercise 1: Create Basic API Routes

  1. Create a new Laravel project or use existing one
  2. Open routes/api.php
  3. Create GET /api/products route that returns 5 products
  4. Test in browser: http://localhost:8000/api/products
  5. Verify JSON response

Exercise 2: Install and Use Postman

  1. Download and install Postman
  2. Create a new collection named "Laravel API"
  3. Test your /api/products endpoint
  4. Save the request in your collection
  5. Take a screenshot of successful response

Exercise 3: Build Complete CRUD API

  1. Create routes for /api/tasks resource
  2. Implement GET /api/tasks (list all)
  3. Implement GET /api/tasks/{id} (get one)
  4. Implement POST /api/tasks (create)
  5. Use array for data storage (not database yet)
  6. Test all endpoints in Postman

Exercise 4: Handle Different Status Codes

  1. Create endpoint that returns 200 for success
  2. Create endpoint that returns 201 when creating
  3. Create endpoint that returns 404 for not found
  4. Add validation that returns 422 on error
  5. Test each status code in Postman

Exercise 5: Query Parameters

  1. Create GET /api/users endpoint
  2. Accept ?role= query parameter
  3. Filter results based on role
  4. Test: /api/users?role=admin
  5. Return filtered JSON response

๐ŸŽฏ Today's Deliverable

โœ… Working REST API with GET and POST Endpoints

Requirements:

  • Laravel project with API routes configured
  • At least 3 GET endpoints returning different data
  • At least 2 POST endpoints with validation
  • Proper JSON responses with status codes
  • Postman collection with all requests saved
  • Screenshot of Postman tests showing:
    • Successful GET request (200)
    • Successful POST request (201)
    • 404 Not Found error
    • 422 Validation error
  • Document your API endpoints in comments

๐Ÿ“š Summary

๐Ÿ”œ What's Next?

In Day 2, we'll learn about: