Build robust API routes with validation, error handling, and middleware for Google Antigravity applications.
# API Route Handler Patterns for Google Antigravity
Next.js API routes provide a powerful way to build backend functionality. Google Antigravity's Gemini 3 helps you implement type-safe, secure APIs with proper validation, error handling, and middleware patterns.
## API Route Setup
Create well-structured API routes with proper typing:
```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
const createUserSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(50),
role: z.enum(["USER", "ADMIN"]).optional(),
});
export async function GET(request: NextRequest) {
try {
const session = await auth();
if (!session) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);
}
const { searchParams } = request.nextUrl;
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "10");
const search = searchParams.get("search") || "";
const skip = (page - 1) * limit;
const [users, total] = await Promise.all([
prisma.user.findMany({
where: {
OR: [
{ name: { contains: search, mode: "insensitive" } },
{ email: { contains: search, mode: "insensitive" } },
],
},
skip,
take: limit,
select: {
id: true,
email: true,
name: true,
role: true,
createdAt: true,
},
orderBy: { createdAt: "desc" },
}),
prisma.user.count({
where: {
OR: [
{ name: { contains: search, mode: "insensitive" } },
{ email: { contains: search, mode: "insensitive" } },
],
},
}),
]);
return NextResponse.json({
data: users,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
},
});
} catch (error) {
console.error("GET /api/users error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session || session.user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Forbidden" },
{ status: 403 }
);
}
const body = await request.json();
const validatedData = createUserSchema.safeParse(body);
if (!validatedData.success) {
return NextResponse.json(
{ error: "Validation failed", details: validatedData.error.flatten() },
{ status: 400 }
);
}
const { email, name, role } = validatedData.data;
const existingUser = await prisma.user.findUnique({
where: { email },
});
if (existingUser) {
return NextResponse.json(
{ error: "User with this email already exists" },
{ status: 409 }
);
}
const user = await prisma.user.create({
data: { email, name, role: role || "USER" },
select: {
id: true,
email: true,
name: true,
role: true,
createdAt: true,
},
});
return NextResponse.json({ data: user }, { status: 201 });
} catch (error) {
console.error("POST /api/users error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
```
## Dynamic Route Handler
Handle individual resource operations:
```typescript
// app/api/users/[id]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
const updateUserSchema = z.object({
name: z.string().min(2).max(50).optional(),
role: z.enum(["USER", "ADMIN"]).optional(),
});
interface RouteParams {
params: { id: string };
}
export async function GET(
request: NextRequest,
{ params }: RouteParams
) {
try {
const session = await auth();
if (!session) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);
}
const user = await prisma.user.findUnique({
where: { id: params.id },
select: {
id: true,
email: true,
name: true,
role: true,
createdAt: true,
_count: {
select: { posts: true },
},
},
});
if (!user) {
return NextResponse.json(
{ error: "User not found" },
{ status: 404 }
);
}
return NextResponse.json({ data: user });
} catch (error) {
console.error(`GET /api/users/${params.id} error:`, error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
export async function PATCH(
request: NextRequest,
{ params }: RouteParams
) {
try {
const session = await auth();
if (!session) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);
}
const isOwnProfile = session.user.id === params.id;
const isAdmin = session.user.role === "ADMIN";
if (!isOwnProfile && !isAdmin) {
return NextResponse.json(
{ error: "Forbidden" },
{ status: 403 }
);
}
const body = await request.json();
const validatedData = updateUserSchema.safeParse(body);
if (!validatedData.success) {
return NextResponse.json(
{ error: "Validation failed", details: validatedData.error.flatten() },
{ status: 400 }
);
}
if (validatedData.data.role && !isAdmin) {
return NextResponse.json(
{ error: "Only admins can change user roles" },
{ status: 403 }
);
}
const user = await prisma.user.update({
where: { id: params.id },
data: validatedData.data,
select: {
id: true,
email: true,
name: true,
role: true,
updatedAt: true,
},
});
return NextResponse.json({ data: user });
} catch (error) {
console.error(`PATCH /api/users/${params.id} error:`, error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
export async function DELETE(
request: NextRequest,
{ params }: RouteParams
) {
try {
const session = await auth();
if (!session || session.user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Forbidden" },
{ status: 403 }
);
}
await prisma.user.delete({
where: { id: params.id },
});
return new NextResponse(null, { status: 204 });
} catch (error) {
console.error(`DELETE /api/users/${params.id} error:`, error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
```
## Reusable API Utilities
Create helper functions for common patterns:
```typescript
// lib/api/utils.ts
import { NextResponse } from "next/server";
import { ZodError, ZodSchema } from "zod";
export class ApiError extends Error {
constructor(
public statusCode: number,
message: string,
public details?: unknown
) {
super(message);
this.name = "ApiError";
}
}
export function successResponse<T>(data: T, status = 200) {
return NextResponse.json({ data }, { status });
}
export function errorResponse(error: unknown) {
if (error instanceof ApiError) {
return NextResponse.json(
{ error: error.message, details: error.details },
{ status: error.statusCode }
);
}
if (error instanceof ZodError) {
return NextResponse.json(
{ error: "Validation failed", details: error.flatten() },
{ status: 400 }
);
}
console.error("Unexpected error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
export async function validateBody<T>(
request: Request,
schema: ZodSchema<T>
): Promise<T> {
const body = await request.json();
return schema.parse(body);
}
export function getPaginationParams(url: URL) {
const page = Math.max(1, parseInt(url.searchParams.get("page") || "1"));
const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get("limit") || "10")));
const skip = (page - 1) * limit;
return { page, limit, skip };
}
export function paginatedResponse<T>(
data: T[],
total: number,
page: number,
limit: number
) {
return {
data,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
hasNext: page * limit < total,
hasPrev: page > 1,
},
};
}
```
## Rate Limiting Middleware
Implement rate limiting for API protection:
```typescript
// lib/api/rate-limit.ts
import { NextRequest, NextResponse } from "next/server";
interface RateLimitConfig {
limit: number;
window: number;
}
const requestCounts = new Map<string, { count: number; resetTime: number }>();
export function rateLimit(config: RateLimitConfig) {
return async function middleware(request: NextRequest) {
const ip = request.headers.get("x-forwarded-for")?.split(",")[0] || "anonymous";
const key = `${ip}:${request.nextUrl.pathname}`;
const now = Date.now();
const record = requestCounts.get(key);
if (!record || now > record.resetTime) {
requestCounts.set(key, {
count: 1,
resetTime: now + config.window * 1000,
});
return null;
}
if (record.count >= config.limit) {
return NextResponse.json(
{ error: "Too many requests" },
{
status: 429,
headers: {
"Retry-After": String(Math.ceil((record.resetTime - now) / 1000)),
"X-RateLimit-Limit": String(config.limit),
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": String(record.resetTime),
},
}
);
}
record.count++;
return null;
};
}
```
## Best Practices
1. **Validate all inputs** - Use Zod for type-safe validation
2. **Handle errors consistently** - Use centralized error handling
3. **Implement proper status codes** - Return appropriate HTTP codes
4. **Add rate limiting** - Protect endpoints from abuse
5. **Log errors for debugging** - Include context in error logs
Next.js API routes with Google Antigravity enable robust backend development with intelligent patterns and security best practices.This api prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their api implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For api projects, consider mentioning your framework version, coding style, and any specific libraries you're using.