CPRG-306 Week 12

API Implementation


  • API routes
    • /api/...

RESTful APIs

  • Representational State Transfer (REST)
  • RESTful APIs
    • Use HTTP methods to perform CRUD operations
    • Use URLs to represent resources
    • Use status codes to indicate success or failure

HTTP Methods

  • GET: Retrieve data
  • POST: Create new data
  • PUT: Update existing data
  • PATCH: Partially update existing data
  • DELETE: Delete data

Resources and URLs

  • Resources are represented by URLs
  • URLs are hierarchical
  • URLs can represent collections and individual items
  • e.g. /api/users/123 represents user with id 123
  • e.g. /api/users represents all users
  • e.g. /api/users/123/orders/777 represents order id 777 for user with id 123

Examples

  • GET /api/users/123 will return user object with id 123
  • POST /api/users with request body will create a new user
  • PUT /api/users/123 with request body will update user
  • DELETE /api/users/123 will delete user with id 123

API Implementation

  • In Next.js API routes are implemented using route.js files in any folder, usually in an api folder
  • API routes are server-side code only

Demo: 3 Parts

  • Part 1
    • Simple API (GET only)
  • Part 2
    • API with GET, POST, PUT, PATCH, and DELETE methods for /api/dogs and /api/dogs/:id
  • Part 3
    • Validation of request body

Demo: For Each Part

  • API implementation with route.js
  • Test the API using VS Code extension REST Client
  • Consume the API from the front-end using fetch