Create Express.js API routes and endpoints for AI Code Studio Pro backend. Use when adding new API endpoints, updating server.ts, or creating REST/GraphQL APIs.
server.ts with new functionalityAsk the user:
/api/users, /api/projects/:id)// server.ts
// Add route handler
app.post('/api/users', async (req, res) => {
try {
const { name, email } = req.body;
// Validate input
if (!name || !email) {
return res.status(400).json({
error: 'Name and email are required'
});
}
// Business logic here
const user = await createUser({ name, email });
res.status(201).json({
success: true,
data: user
});
} catch (error: any) {
console.error('Error creating user:', error);
res.status(500).json({
error: error.message || 'Failed to create user'
});
}
});
// src/types/api.ts
export interface CreateUserRequest {
name: string;
email: string;
}
export interface CreateUserResponse {
success: boolean;
data: User;
}
export interface ApiError {
error: string;
message?: string;
}
import { z } from 'zod';
const CreateUserSchema = z.object({
name: z.string().min(1).max(100),
email: z.string().email()
});
app.post('/api/users', async (req, res) => {
try {
const parsed = CreateUserSchema.parse(req.body);
// ... rest of handler
} catch (error: any) {
if (error instanceof z.ZodError) {
return res.status(400).json({
error: 'Validation failed',
details: error.errors
});
}
// ... handle other errors
}
});
// tests/api/users.test.ts
import { describe, it, expect } from 'vitest';
describe('POST /api/users', () => {
it('creates a new user', async () => {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Test', email: '[email protected]' })
});
expect(response.status).toBe(201);
const data = await response.json();
expect(data.success).toBe(true);
});
it('validates required fields', async () => {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
expect(response.status).toBe(400);
});
});
try {
// Operation
} catch (error: any) {
console.error('Operation failed:', error);
res.status(500).json({
error: error.message || 'An unexpected error occurred'
});
}
// Success
{
success: true,
data: { ... },
message?: string
}
// Error
{
success: false,
error: string,
details?: any
}
interface PaginatedResponse<T> {
data: T[];
total: number;
page: number;
limit: number;
hasMore: boolean;
}
User: "Add an endpoint to create a new project"
You:
POST /api/projects route to server.ts