Intermediate

API Development with AI

Lesson 2 of 4 Estimated Time 50 min

API Development with AI

Building REST APIs, GraphQL services, or other API-based systems requires careful design and implementation. AI excels at API generation: from endpoint structure through validation, error handling, and documentation.

Designing API Contracts

Defining Your API Specification

Before implementing, specify what your API will do:

You: "I'm building a user management API. Endpoints:
     1. POST /users - create user
     2. GET /users/:id - get user
     3. PUT /users/:id - update user
     4. DELETE /users/:id - delete user

     Response format: JSON with status codes
     Requirements: validation, error handling, pagination"

AI: [Generates OpenAPI specification]

Generating OpenAPI/Swagger Specs

You: "Generate OpenAPI 3.0 spec for these endpoints:
     [describe endpoints]

     Include:
     - Request schemas
     - Response schemas  
     - Status codes
     - Error responses"

AI: [Generates complete OpenAPI spec]

You can use this spec as documentation and for code generation.

REST API Implementation

Endpoint Generation

You: "Generate Express endpoints for:
     - GET /products - list all
     - GET /products/:id - get one
     - POST /products - create
     - PUT /products/:id - update
     - DELETE /products/:id - delete

     Include validation and error handling
     Use our patterns: [show pattern examples]"

AI: [Generates complete CRUD endpoints]

Request Validation

You: "I need to validate user registration:
     - Email required, valid format
     - Password required, min 8 chars, complexity rules
     - Name required, max 100 chars
     - Age optional, must be >18 if provided

     Framework: Express + Joi"

AI: [Generates validation schema]

Error Handling

You: "Standard error responses:
     - 400 Bad Request: validation failed
     - 401 Unauthorized: not authenticated
     - 403 Forbidden: not authorized
     - 404 Not Found: resource doesn't exist
     - 500 Server Error: internal error

     Framework: Express
     Return format: {status, message, errors}"

AI: [Generates consistent error handling]

API Testing

Generating Integration Tests

You: "Generate tests for these endpoints:
     [paste endpoint code]

     Test:
     - Happy path (valid request)
     - Validation errors
     - Authorization errors
     - Not found errors

     Framework: Supertest + Jest"

AI: [Generates comprehensive tests]

Generating API Requests

You: "Generate example requests for:
     - Create user
     - Update user
     - Delete user

     Include headers, body, expected responses"

AI: [Generates cURL, Postman, or REST client examples]

GraphQL APIs

Schema Generation

You: "GraphQL schema for:
     - Users (id, name, email)
     - Posts (id, title, content, author)
     - Comments (id, text, author, post)

     Include relationships"

AI: [Generates GraphQL schema]

Resolver Implementation

You: "Implement resolvers for:
     [paste GraphQL schema]

     Database: PostgreSQL
     ORM: Sequelize"

AI: [Generates all resolvers]

API Security

Input Sanitization

You: "I'm accepting user-provided content:
     - HTML snippets
     - Markdown text
     - File names

     How should I sanitize each?"

AI: [Explains sanitization for each type]
     [Provides code examples]

Rate Limiting

You: "Implement rate limiting:
     - 100 requests per minute per IP
     - 1000 per hour per user
     - Burst protection

     Framework: Express"

AI: [Generates rate limiting middleware]

CORS Configuration

You: "Configure CORS for:
     - Frontend: https://app.example.com
     - Admin: https://admin.example.com
     - Staging: https://staging.example.com

     Allow specific methods: GET, POST, PUT
     Framework: Express"

AI: [Generates CORS middleware]

API Versioning

Version Strategy

You: "I need to version my API. Should I use:
     A) URL path: /v1/users, /v2/users
     B) Header: Accept: application/vnd.api.v2+json
     C) Query param: /users?api_version=2

     Which is best? Pros/cons?"

AI: [Explains each approach with examples]

Migration Guide

You: "I'm upgrading from v1 to v2:
     - /users returns new schema
     - Some fields renamed
     - New required fields

     How do I migrate without breaking v1 clients?"

AI: [Shows deprecation strategy and migration plan]

Real-World API Scenarios

Scenario 1: Pagination

You: "Implement pagination:
     - /products?page=1&limit=20
     - Return total count
     - Include hasMore flag

     Framework: Express + MongoDB"

AI: [Generates pagination implementation]

Scenario 2: Filtering and Searching

You: "Search and filter products:
     - GET /products?search=shoes
     - GET /products?category=footwear&minPrice=10&maxPrice=100
     - Support combinations
     - Sortable by price, rating, newest"

AI: [Generates filtering logic]

Scenario 3: Nested Resources

You: "API structure:
     - /users/:id/posts (user's posts)
     - /users/:id/posts/:postId/comments (post's comments)

     Generate endpoints with proper routing"

AI: [Generates nested resource endpoints]

Scenario 4: Async Operations

You: "Generate a large report (1000+ rows).
     Can't send in single response (too large).
     Should I: queue job, return ID, poll for status?

     Framework: Express + Bull/Celery"

AI: [Shows async job pattern]

Response Formatting

Consistent Response Format

You: "Define consistent response format:
     - Success: {status: 'success', data: {...}}
     - Error: {status: 'error', message: '...', code: '...'}"

AI: [Generates response wrapper middleware]

Pagination Response

You: "Format for paginated responses:
     - Include items array
     - Include metadata (total, page, hasMore)
     - Include links (next, previous)"

AI: [Generates pagination response format]

API Documentation

Auto-Generated Documentation

You: "Generate Swagger/OpenAPI docs from my endpoints:
     [paste endpoint code]

     Framework: Express"

AI: [Generates Swagger configuration]
     [Generates endpoint descriptions]

You can then view docs at /api/docs.

Writing API Docs

You: "Document this endpoint for developers:
     [paste endpoint code]

     Include: purpose, params, request body, responses, errors"

AI: [Generates markdown documentation]

Exercises

  1. API Design: Design an API for a use case you care about:

    • List endpoints needed
    • Define request/response formats
    • Ask AI to generate OpenAPI spec
  2. REST Implementation: Implement CRUD API:

    • Generate endpoints
    • Add validation
    • Add error handling
    • Generate tests
  3. API Documentation: Generate complete docs for an API:

    • OpenAPI spec
    • Example requests
    • Error codes
    • Authentication flow
  4. Error Handling: Design error handling:

    • List error types
    • Ask AI to generate consistent error responses
    • Implement across all endpoints
  5. Testing: Generate comprehensive tests:

    • Happy path
    • Validation errors
    • Authorization errors
    • Edge cases