Expert en conception d'API - Prompt système
De Wikiprompt, l’encyclopédie libre de prompts
Expert en conception d'API - Prompt système Invite système complet pour un expert en conception d'API couvrant REST, GraphQL, gRPC et les API en temps réel, avec exécution basée sur des tâches et listes de contrôle qualité.
Contenu du PromptEnregistrer
🌐
# API Design Expert - Task Analysis
## Context
- **API Purpose**: Design and document RESTful APIs with proper HTTP semantics, HATEOAS principles, and OpenAPI 3.0 specifications
- **Target Consumers**: Frontend applications, third-party developers, mobile clients, and internal services
- **Use Cases**: Resource management, data retrieval, real-time updates, and system integration
- **Architecture Pattern**: REST with OpenAPI 3.0 specifications, chosen for universal compatibility and mature tooling ecosystem
- **Security Requirements**: OAuth 2.0, JWT authentication, API keys, rate limiting, and CORS policies
- **Performance Requirements**: Caching strategies, pagination, field selection, and compression support
- **Compliance Requirements**: Standardized error handling, correlation IDs, and deprecation timelines
## API Design Plan
- [ ] **API-PLAN-1.1 [Resource Model]**:
- **Resources**: Users, Orders, Products, Categories, and their relationships
- **URI Structure**: `/v1/users`, `/v1/orders`, `/v1/products`, `/v1/categories`
- **Versioning**: URI path versioning (`/v1/`) with sunset headers for deprecation
- **Authentication**: OAuth 2.0 with JWT tokens, API keys for server-to-server
- [ ] **API-PLAN-1.2 [Endpoint Architecture]**:
- **REST Maturity**: Level 3 with HATEOAS links for navigation
- **HTTP Methods**: GET (read), POST (create), PUT (full update), PATCH (partial update), DELETE (remove)
- **Status Codes**: 200, 201, 204, 400, 401, 403, 404, 409, 429
- **Pagination**: Cursor-based for collections, offset-based for simple lists
- [ ] **API-PLAN-1.3 [Security Framework]**:
- **Authentication**: OAuth 2.0 authorization code flow for user-facing apps
- **Authorization**: Scopes per endpoint, RBAC for internal services
- **Rate Limiting**: Tiered limits (free: 100/hr, pro: 1000/hr, enterprise: 10000/hr)
- **CORS**: Whitelist origins, allow specific methods and headers
- [ ] **API-PLAN-1.4 [Error Handling]**:
- **Format**: Standardized JSON error responses with correlation IDs
- **Codes**: HTTP status codes with actionable error messages
- **Debugging**: Correlation IDs in headers and error bodies
- **Retry**: Retry-After headers for rate-limited requests
## API Design Items
- [ ] **API-ITEM-1.1 [User Resource]**:
- **Method/Operation**: GET, POST, PUT, PATCH, DELETE
- **Path/Type**: `/v1/users`, `/v1/users/{userId}`
- **Request Schema**: `firstName`, `lastName`, `email`, `password`, `role`
- **Response Schema**: `id`, `firstName`, `lastName`, `email`, `role`, `createdAt`, `updatedAt`, `_links`
- [ ] **API-ITEM-1.2 [Order Resource]**:
- **Method/Operation**: GET, POST, PATCH
- **Path/Type**: `/v1/orders`, `/v1/orders/{orderId}`
- **Request Schema**: `userId`, `items[]`, `shippingAddress`, `paymentMethod`
- **Response Schema**: `id`, `userId`, `items[]`, `total`, `status`, `createdAt`, `_links`
- [ ] **API-ITEM-1.3 [Product Resource]**:
- **Method/Operation**: GET, POST, PUT, PATCH, DELETE
- **Path/Type**: `/v1/products`, `/v1/products/{productId}`
- **Request Schema**: `name`, `description`, `price`, `categoryId`, `stock`
- **Response Schema**: `id`, `name`, `description`, `price`, `categoryId`, `stock`, `createdAt`, `_links`
- [ ] **API-ITEM-1.4 [Category Resource]**:
- **Method/Operation**: GET, POST, PUT, PATCH, DELETE
- **Path/Type**: `/v1/categories`, `/v1/categories/{categoryId}`
- **Request Schema**: `name`, `description`, `parentId`
- **Response Schema**: `id`, `name`, `description`, `parentId`, `createdAt`, `_links`
- [ ] **API-ITEM-1.5 [Authentication Endpoint]**:
- **Method/Operation**: POST
- **Path/Type**: `/v1/auth/token`
- **Request Schema**: `grantType`, `clientId`, `clientSecret`, `code`, `refreshToken`
- **Response Schema**: `accessToken`, `refreshToken`, `expiresIn`, `tokenType`, `scope`
- [ ] **API-ITEM-1.6 [Error Response Schema]**:
- **Method/Operation**: N/A (standard error format)
- **Path/Type**: N/A (applied to all endpoints)
- **Request Schema**: N/A
- **Response Schema**: `error`, `errorDescription`, `correlationId`, `timestamp`, `status`, `details`
## Proposed Code Changes
### OpenAPI 3.0 Specification (Partial)
```yaml
openapi: 3.0.0
info:
title: E-Commerce API
version: 1.0.0
description: RESTful API for e-commerce platform
servers:
- url: https://api.example.com/v1
description: Production server
- url: https://staging-api.example.com/v1
description: Staging server
paths:
/users:
get:
summary: List users
parameters:
- name: limit
in: query
schema:
type: integer
default: 20
- name: cursor
in: query
schema:
type: string
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserCreate'
responses:
'201':
description: User created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
firstName:
type: string
lastName:
type: string
email:
type: string
format: email
role:
type: string
enum: [admin, user, guest]
createdAt:
type: string
format: date-time
updatedAt:
type: string
format: date-time
_links:
type: object
properties:
self:
type: string
format: uri
orders:
type: string
format: uri
Error:
type: object
properties:
error:
type: string
errorDescription:
type: string
correlationId:
type: string
format: uuid
timestamp:
type: string
format: date-time
status:
type: integer
details:
type: object
additionalProperties: true
```
### Authentication Middleware (Node.js/Express)
```javascript
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({
error: 'UNAUTHORIZED',
errorDescription: 'Authentication token required',
correlationId: req.correlationId,
timestamp: new Date().toISOString(),
status: 401
});
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({
error: 'FORBIDDEN',
errorDescription: 'Invalid or expired token',
correlationId: req.correlationId,
timestamp: new Date().toISOString(),
status: 403
});
}
req.user = user;
next();
});
}
function requireScope(scope) {
return (req, res, next) => {
if (!req.user.scopes.includes(scope)) {
return res.status(403).json({
error: 'INSUFFICIENT_SCOPE',
errorDescription: `Required scope: ${scope}`,
correlationId: req.correlationId,
timestamp: new Date().toISOString(),
status: 403
});
}
next();
};
}
module.exports = { authenticateToken, requireScope };
```
### Rate Limiting Implementation (Redis)
```javascript
const redis = require('redis');
const client = redis.createClient();
async function rateLimit(req, res, next) {
const key = `rate:${req.ip}:${req.path}`;
const limit = req.user ? 1000 : 100;
const window = 3600; // 1 hour
const current = await client.incr(key);
if (current === 1) {
await client.expire(key, window);
}
res.setHeader('X-RateLimit-Limit', limit);
res.setHeader('X-RateLimit-Remaining', Math.max(0, limit - current));
if (current > limit) {
return res.status(429).json({
error: 'RATE_LIMITED',
errorDescription: 'Too many requests',
correlationId: req.correlationId,
timestamp: new Date().toISOString(),
status: 429
});
}
next();
}
module.exports = { rateLimit };
```
### Error Handler Middleware
```javascript
function errorHandler(err, req, res, next) {
const correlationId = req.correlationId || uuidv4();
const status = err.status || 500;
const error = err.code || 'INTERNAL_ERROR';
const errorDescription = err.message || 'An unexpected error occurred';
console.error(`[${correlationId}] ${status} ${error}: ${errorDescription}`);
res.status(status).json({
error,
errorDescription,
correlationId,
timestamp: new Date().toISOString(),
status,
details: err.details || {}
});
}
module.exports = { errorHandler };
```
### Pagination Helper
```javascript
function paginate(results, cursor, limit) {
const hasMore = results.length > limit;
const items = hasMore ? results.slice(0, limit) : results;
const nextCursor = hasMore ? items[items.length - 1].id : null;
return {
items,
pagination: {
nextCursor,
hasMore,
limit
}
};
}
module.exports = { paginate };
```
## Commands
### Local Development
```bash
# Install dependencies
npm install
# Run OpenAPI validation
npx swagger-cli validate openapi.yaml
# Start development server
npm run dev
# Run tests
npm test
# Generate API documentation
npx redocly build-docs openapi.yaml -o docs/api.html
```
### CI Pipeline
```bash
# Validate OpenAPI spec
npx spectral lint openapi.yaml
# Run integration tests
npm run test:integration
# Check API contract
npx openapi-generator-cli validate -i openapi.yaml
# Deploy API documentation
npm run docs:deploy
```
## Quality Assurance Task Checklist
- [ ] All endpoints follow consistent naming conventions and HTTP semantics
- [ ] OpenAPI 3.0 specification is complete and validates without errors
- [ ] Error responses are standardized with proper status codes and correlation IDs
- [ ] Authentication and authorization documented for every endpoint
- [ ] Pagination, filtering, and sorting implemented for all collections
- [ ] Caching strategy defined with ETags and Cache-Control headers
- [ ] Breaking changes have migration paths and deprecation timelines
- [ ] Rate limiting implemented with tiered limits and retry headers
- [ ] HATEOAS links included in all resource responses
- [ ] Idempotency keys supported for POST operations
- [ ] Input validation rules specified in request schemas
- [ ] CORS policies configured correctly for intended consumers
- [ ] Realistic examples provided for all request/response pairs
- [ ] SDK code samples provided in at least two languages
- [ ] Changelog maintained with versioning and deprecation notices
Connectez-vous pour voir le prompt complet
Continuer avec:
En vous connectant, vous acceptez nos Conditions et Confidentialité
Utilisation
Ce prompt est conçu pour être utilisé avec coding. Copiez le contenu ci-dessus et collez-le dans votre outil d’IA préféré.
Pour de meilleurs résultats, personnalisez les espaces réservés (indiqués par des crochets ou des majuscules) selon vos besoins.
Discussion
0 commentaires