Przejdź do głównej zawartości

API Development with AI

Ta treść nie jest jeszcze dostępna w Twoim języku.

Accelerate API development from design to deployment with AI assistance that understands modern API patterns and best practices.

Design-First Approach

Generate OpenAPI/GraphQL schemas from requirements, ensuring consistent API design across services.

Implementation Speed

Transform API specifications into working code with proper validation, error handling, and documentation.

Testing Automation

Generate comprehensive test suites including unit tests, integration tests, and contract tests.

Documentation

Maintain always up-to-date API documentation with examples, SDKs, and interactive playgrounds.

  1. Requirements to OpenAPI

    # Natural language to OpenAPI
    "Design a REST API for a task management system:
    - CRUD operations for tasks
    - User authentication
    - Task assignment and status updates
    - Filtering and pagination
    - Follow REST best practices"
    # AI generates OpenAPI 3.0 spec:
    openapi: 3.0.0
    info:
    title: Task Management API
    version: 1.0.0
    paths:
    /tasks:
    get:
    summary: List tasks
    parameters:
    - name: status
    in: query
    schema:
    type: string
    enum: [todo, in_progress, done]
    - name: page
    in: query
    schema:
    type: integer
    default: 1
    responses:
    200:
    description: Paginated task list
    content:
    application/json:
    schema:
    $ref: '#/components/schemas/TaskList'
  2. Resource Modeling

    Terminal window
    "Design RESTful resources for e-commerce:
    - Follow REST maturity level 3 (HATEOAS)
    - Proper HTTP methods and status codes
    - Resource relationships
    - Versioning strategy"
  3. Implementation Generation

    // Generate from OpenAPI
    "Implement the tasks API endpoint:
    - Express.js with TypeScript
    - Input validation
    - Error handling
    - Database integration
    - Authentication middleware"
    // AI generates:
    import { Router } from 'express';
    import { body, query, validationResult } from 'express-validator';
    const router = Router();
    router.get('/tasks',
    authenticate,
    query('status').optional().isIn(['todo', 'in_progress', 'done']),
    query('page').optional().isInt({ min: 1 }),
    async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
    }
    const { status, page = 1 } = req.query;
    const tasks = await taskService.list({
    status,
    page,
    userId: req.user.id
    });
    res.json({
    data: tasks,
    links: generatePaginationLinks(req, tasks.totalPages)
    });
    }
    );
# Generate GraphQL schema
"Design GraphQL API for blog platform:
- Posts, authors, comments
- Real-time subscriptions
- Complex filtering
- Relay-style pagination"
type Post {
id: ID!
title: String!
content: String!
author: User!
comments(first: Int, after: String): CommentConnection!
createdAt: DateTime!
updatedAt: DateTime!
}
type Query {
post(id: ID!): Post
posts(
filter: PostFilter
first: Int
after: String
): PostConnection!
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload!
updatePost(input: UpdatePostInput!): UpdatePostPayload!
}
type Subscription {
postUpdated(id: ID!): Post!
commentAdded(postId: ID!): Comment!
}

Protocol Buffer Definition

# Generate proto files
"Design gRPC service for user management:
- User CRUD operations
- Streaming for bulk operations
- Field masks for partial updates
- Error handling"
syntax = "proto3";
package user.v1;
import "google/protobuf/field_mask.proto";
import "google/protobuf/timestamp.proto";
service UserService {
rpc GetUser(GetUserRequest) returns (GetUserResponse);
rpc ListUsers(ListUsersRequest) returns (ListUsersResponse);
rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse);
rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse);
// Streaming
rpc StreamUsers(StreamUsersRequest) returns (stream User);
rpc BulkCreateUsers(stream CreateUserRequest) returns (BulkCreateUsersResponse);
}
message User {
string id = 1;
string email = 2;
string name = 3;
google.protobuf.Timestamp created_at = 4;
google.protobuf.Timestamp updated_at = 5;
}
message UpdateUserRequest {
string id = 1;
User user = 2;
google.protobuf.FieldMask field_mask = 3;
}
# Generate auth middleware
"Implement JWT authentication with:
- Token generation and validation
- Refresh token rotation
- Role-based access control
- API key management
- OAuth2 integration"
// JWT middleware
export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = extractToken(req);
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
const payload = await verifyToken(token);
const user = await userService.findById(payload.userId);
if (!user || user.deletedAt) {
return res.status(401).json({ error: 'Invalid token' });
}
req.user = user;
next();
} catch (error) {
if (error.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired' });
}
return res.status(401).json({ error: 'Invalid token' });
}
};
// Role-based authorization
export const authorize = (...roles: string[]) => {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return res.status(401).json({ error: 'Authentication required' });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
};
// Consistent error responses
"Create error handling middleware:
- Standard error format
- Proper HTTP status codes
- Error logging
- Client-friendly messages"
class APIError extends Error {
constructor(
public statusCode: number,
public message: string,
public code?: string,
public details?: any
) {
super(message);
}
}
const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
logger.error(err);
if (err instanceof APIError) {
return res.status(err.statusCode).json({
error: {
message: err.message,
code: err.code,
details: err.details
}
});
}
if (err.name === 'ValidationError') {
return res.status(400).json({
error: {
message: 'Validation failed',
code: 'VALIDATION_ERROR',
details: extractValidationErrors(err)
}
});
}
res.status(500).json({
error: {
message: 'Internal server error',
code: 'INTERNAL_ERROR'
}
});
};
  1. Unit Tests

    # Generate unit tests
    "Create unit tests for TaskService:
    - Mock dependencies
    - Test all methods
    - Edge cases
    - Error scenarios"
    describe('TaskService', () => {
    let taskService: TaskService;
    let mockRepo: jest.Mocked<TaskRepository>;
    beforeEach(() => {
    mockRepo = createMockRepository();
    taskService = new TaskService(mockRepo);
    });
    describe('createTask', () => {
    it('should create task with valid data', async () => {
    const input = { title: 'Test Task', userId: '123' };
    mockRepo.create.mockResolvedValue({ id: '1', ...input });
    const result = await taskService.createTask(input);
    expect(result).toMatchObject(input);
    expect(mockRepo.create).toHaveBeenCalledWith(input);
    });
    it('should throw on duplicate title', async () => {
    mockRepo.create.mockRejectedValue(new UniqueConstraintError());
    await expect(taskService.createTask({ title: 'Duplicate' }))
    .rejects.toThrow(APIError);
    });
    });
    });
  2. Integration Tests

    # Generate API integration tests
    "Create integration tests:
    - Test actual HTTP endpoints
    - Database integration
    - Authentication flow
    - Error responses"
    describe('Tasks API', () => {
    beforeAll(async () => {
    await setupTestDatabase();
    });
    describe('GET /tasks', () => {
    it('should return paginated tasks', async () => {
    const token = await getAuthToken();
    const response = await request(app)
    .get('/api/tasks?page=1&limit=10')
    .set('Authorization', `Bearer ${token}`)
    .expect(200);
    expect(response.body).toMatchObject({
    data: expect.any(Array),
    pagination: {
    page: 1,
    limit: 10,
    total: expect.any(Number)
    }
    });
    });
    });
    });
  3. Contract Tests

    # Generate contract tests
    "Create Pact tests for microservices:
    - Consumer-driven contracts
    - Provider verification
    - Schema validation"
# Generate k6 load tests
"Create load test scenarios:
- Gradual ramp-up
- Spike testing
- Stress testing
- Soak testing"
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '2m', target: 100 }, // Ramp up
{ duration: '5m', target: 100 }, // Stay at 100
{ duration: '2m', target: 200 }, // Spike
{ duration: '5m', target: 200 }, // Sustained load
{ duration: '2m', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95) < 500'], // 95% of requests under 500ms
http_req_failed: ['rate < 0.1'], // Error rate under 10%
},
};
export default function () {
const token = getAuthToken();
const response = http.get('https://api.example.com/tasks', {
headers: { Authorization: `Bearer ${token}` },
});
check(response, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
# Generate API documentation
"Create comprehensive API docs:
- Interactive API explorer
- Code examples in multiple languages
- Authentication guide
- Rate limiting info
- Changelog"
// Swagger UI configuration
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'Task Management API',
version: '1.0.0',
description: 'Complete task management system',
contact: {
email: 'api@example.com'
}
},
servers: [
{ url: 'https://api.example.com/v1', description: 'Production' },
{ url: 'https://staging-api.example.com/v1', description: 'Staging' }
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT'
}
}
}
},
apis: ['./src/routes/*.ts'], // Path to API routes
};

Multi-Language SDKs

Terminal window
# Generate client SDKs
"Generate SDKs from OpenAPI spec:
- TypeScript/JavaScript
- Python
- Go
- Java
- Include authentication helpers
- Retry logic
- Type safety"
# Using OpenAPI Generator
openapi-generator generate -i api.yaml -g typescript-axios -o ./sdk/typescript
openapi-generator generate -i api.yaml -g python -o ./sdk/python
openapi-generator generate -i api.yaml -g go -o ./sdk/go
# Implement API versioning
"Design versioning strategy:
- URL versioning (/v1, /v2)
- Header versioning
- Deprecation warnings
- Migration guides"
// URL-based versioning
app.use('/api/v1', v1Routes);
app.use('/api/v2', v2Routes);
// Header-based versioning
const versionMiddleware = (req: Request, res: Response, next: NextFunction) => {
const version = req.headers['api-version'] || 'v1';
req.apiVersion = version;
// Add deprecation warnings
if (version === 'v1') {
res.setHeader('X-API-Deprecation', 'Version 1 will be deprecated on 2025-12-31');
res.setHeader('X-API-Migration', 'https://docs.api.com/migration-v2');
}
next();
};
# Implement caching
"Add caching layers:
- Redis for session data
- CDN for static content
- Database query caching
- Response caching
- Cache invalidation"
// Redis caching middleware
const cache = (duration: number) => {
return async (req: Request, res: Response, next: NextFunction) => {
const key = `cache:${req.originalUrl}`;
try {
const cached = await redis.get(key);
if (cached) {
return res.json(JSON.parse(cached));
}
} catch (error) {
logger.error('Cache error:', error);
}
// Store original json method
const originalJson = res.json;
// Override json method
res.json = function(data) {
// Cache the response
redis.setex(key, duration, JSON.stringify(data))
.catch(err => logger.error('Cache set error:', err));
// Call original json method
return originalJson.call(this, data);
};
next();
};
};
// Usage
router.get('/popular-posts', cache(300), async (req, res) => {
const posts = await postService.getPopular();
res.json(posts);
});
# Implement rate limiting
"Add rate limiting:
- Per-user limits
- API key tiers
- Endpoint-specific limits
- Graceful degradation"
const rateLimiter = createRateLimiter({
windowMs: 15 * 60 * 1000, // 15 minutes
max: (req) => {
// Different limits based on user tier
if (req.user?.tier === 'premium') return 1000;
if (req.user?.tier === 'basic') return 100;
return 50; // Anonymous users
},
message: 'Too many requests',
standardHeaders: true,
legacyHeaders: false,
});
  1. Design First

    • Start with API specifications
    • Get stakeholder agreement
    • Version from day one
    • Plan for deprecation
  2. Security by Default

    • Authenticate all endpoints
    • Validate all inputs
    • Use HTTPS only
    • Implement rate limiting
  3. Developer Experience

    • Comprehensive documentation
    • Interactive API explorer
    • Multiple SDK languages
    • Clear error messages
  4. Performance Focus

    • Implement caching
    • Use pagination
    • Optimize queries
    • Monitor response times

API development with AI transforms the entire lifecycle from design to deployment, enabling teams to build robust, well-documented APIs that scale with business needs while maintaining high quality standards.