Code Generation in AI
From the AI Prompting cheat sheet · Code Generation & Technical · verified Jul 2026
Code Generation
Generate clean, functional code with specifications
javascript
NAME: Code Generation Template
PURPOSE: Generate production-ready code with proper structure and error handling
TEMPLATE:
Write a [LANGUAGE] [COMPONENT TYPE] that:
Functionality:
- [FEATURE 1]
- [FEATURE 2]
- [FEATURE 3]
Requirements:
- Follow [STYLE GUIDE/CONVENTION]
- Include error handling
- Add comprehensive comments
- Make it production-ready
Constraints:
- [PERFORMANCE REQUIREMENT]
- [COMPATIBILITY REQUIREMENT]
- [SECURITY CONSIDERATION]
Include:
- Type definitions (if applicable)
- Unit test examples
- Usage documentation
EXAMPLE:
Write a TypeScript REST API client that:
Functionality:
- Supports GET, POST, PUT, DELETE methods
- Handles authentication via Bearer tokens
- Implements automatic retry logic
Requirements:
- Follow clean code principles
- Include error handling
- Add comprehensive comments
- Make it production-ready
Constraints:
- Keep bundle size under 10KB
- Support both Node.js and browser environments
- No external dependencies except native fetch
Include:
- Type definitions
- Unit test examples
- Usage documentation
OUTPUT:
/**
* Lightweight REST API Client
* Supports common HTTP methods with automatic retry and auth
*/
interface APIClientConfig {
baseURL: string;
headers?: Record<string, string>;
maxRetries?: number;
retryDelay?: number;
}
interface RequestOptions extends RequestInit {
params?: Record<string, any>;
retry?: boolean;
}
class APIClient {
private config: Required<APIClientConfig>;
constructor(config: APIClientConfig) {
this.config = {
baseURL: config.baseURL,
headers: config.headers || {},
maxRetries: config.maxRetries || 3,
retryDelay: config.retryDelay || 1000,
};
}
/**
* Set authorization token
*/
setAuthToken(token: string): void {
this.config.headers['Authorization'] = `Bearer ${token}`;
}
/**
* Generic request method with retry logic
*/
private async request<T>(
endpoint: string,
options: RequestOptions = {}
): Promise<T> {
const url = new URL(endpoint, this.config.baseURL);
// Add query parameters
if (options.params) {
Object.entries(options.params).forEach(([key, value]) =>
url.searchParams.append(key, value)
);
}
const { retry = true, params, ...fetchOptions } = options;
const config: RequestInit = {
...fetchOptions,
headers: {
...this.config.headers,
...fetchOptions.headers,
},
};
let lastError: Error;
const attempts = retry ? this.config.maxRetries : 1;
for (let i = 0; i < attempts; i++) {
try {
const response = await fetch(url.toString(), config);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
lastError = error as Error;
if (i < attempts - 1) {
await new Promise(r => setTimeout(r, this.config.retryDelay * (i + 1)));
}
}
}
throw lastError!;
}
// HTTP methods
async get<T>(endpoint: string, options?: RequestOptions): Promise<T> {
return this.request<T>(endpoint, { ...options, method: 'GET' });
}
async post<T>(endpoint: string, data?: any, options?: RequestOptions): Promise<T> {
return this.request<T>(endpoint, {
...options,
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json', ...options?.headers },
});
}
async put<T>(endpoint: string, data?: any, options?: RequestOptions): Promise<T> {
return this.request<T>(endpoint, {
...options,
method: 'PUT',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json', ...options?.headers },
});
}
async delete<T>(endpoint: string, options?: RequestOptions): Promise<T> {
return this.request<T>(endpoint, { ...options, method: 'DELETE' });
}
}
// Usage Example:
const api = new APIClient({
baseURL: 'https://api.example.com',
maxRetries: 3,
});
api.setAuthToken('your-token');
// GET request
const users = await api.get('/users', { params: { page: 1 } });
// POST request
const newUser = await api.post('/users', { name: 'John' });
// Unit test example
describe('APIClient', () => {
it('should retry failed requests', async () => {
const api = new APIClient({ baseURL: 'http://localhost' });
// Test implementation...
});
});🎯 Specify language, framework, and patterns
💡 Request documentation and tests
⚡ Include performance and security requirements