Design clean, consistent, and developer-friendly APIs with Google Antigravity
# API Design Patterns for Google Antigravity
Create well-designed, consistent APIs that developers love using with Google Antigravity IDE.
## RESTful API Design
```typescript
// routes/api/v1/users.ts
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { HTTPException } from "hono/http-exception";
const app = new Hono();
// Resource schemas
const userSchema = z.object({
name: z.string().min(1).max(100),
email: z.string().email(),
role: z.enum(["user", "admin"]).default("user")
});
const querySchema = z.object({
page: z.coerce.number().positive().default(1),
limit: z.coerce.number().positive().max(100).default(20),
sort: z.enum(["name", "email", "createdAt"]).default("createdAt"),
order: z.enum(["asc", "desc"]).default("desc"),
search: z.string().optional()
});
// List resources with pagination
app.get("/", zValidator("query", querySchema), async (c) => {
const query = c.req.valid("query");
const { items, total, totalPages } = await userService.list(query);
// Return consistent response envelope
return c.json({
data: items,
meta: {
page: query.page,
limit: query.limit,
total,
totalPages,
hasNext: query.page < totalPages,
hasPrev: query.page > 1
},
links: {
self: `/api/v1/users?page=${query.page}`,
first: "/api/v1/users?page=1",
last: `/api/v1/users?page=${totalPages}`,
next: query.page < totalPages ? `/api/v1/users?page=${query.page + 1}` : null,
prev: query.page > 1 ? `/api/v1/users?page=${query.page - 1}` : null
}
});
});
// Get single resource
app.get("/:id", async (c) => {
const id = c.req.param("id");
const user = await userService.findById(id);
if (!user) {
throw new HTTPException(404, {
message: "User not found",
cause: { code: "USER_NOT_FOUND", id }
});
}
return c.json({
data: user,
links: {
self: `/api/v1/users/${id}`,
orders: `/api/v1/users/${id}/orders`
}
});
});
// Create resource
app.post("/", zValidator("json", userSchema), async (c) => {
const body = c.req.valid("json");
const user = await userService.create(body);
return c.json({ data: user }, 201, {
Location: `/api/v1/users/${user.id}`
});
});
// Update resource (full replacement)
app.put("/:id", zValidator("json", userSchema), async (c) => {
const id = c.req.param("id");
const body = c.req.valid("json");
const user = await userService.update(id, body);
return c.json({ data: user });
});
// Partial update
app.patch("/:id", zValidator("json", userSchema.partial()), async (c) => {
const id = c.req.param("id");
const body = c.req.valid("json");
const user = await userService.patch(id, body);
return c.json({ data: user });
});
// Delete resource
app.delete("/:id", async (c) => {
const id = c.req.param("id");
await userService.delete(id);
return c.body(null, 204);
});
export default app;
```
## Error Response Format
```typescript
// lib/errors.ts
export interface APIError {
status: number;
code: string;
message: string;
details?: Record<string, unknown>;
timestamp: string;
requestId: string;
}
export class AppError extends Error {
constructor(
public status: number,
public code: string,
message: string,
public details?: Record<string, unknown>
) {
super(message);
this.name = "AppError";
}
}
// Error codes
export const ErrorCodes = {
VALIDATION_ERROR: "VALIDATION_ERROR",
NOT_FOUND: "NOT_FOUND",
UNAUTHORIZED: "UNAUTHORIZED",
FORBIDDEN: "FORBIDDEN",
CONFLICT: "CONFLICT",
RATE_LIMITED: "RATE_LIMITED",
INTERNAL_ERROR: "INTERNAL_ERROR"
} as const;
// Error handler middleware
export function errorHandler(err: Error, c: Context) {
const requestId = c.get("requestId");
if (err instanceof AppError) {
return c.json<APIError>({
status: err.status,
code: err.code,
message: err.message,
details: err.details,
timestamp: new Date().toISOString(),
requestId
}, err.status);
}
// Log unexpected errors
console.error("Unhandled error:", err);
return c.json<APIError>({
status: 500,
code: ErrorCodes.INTERNAL_ERROR,
message: "An unexpected error occurred",
timestamp: new Date().toISOString(),
requestId
}, 500);
}
```
## Filtering and Field Selection
```typescript
// lib/query-builder.ts
import { z } from "zod";
// Field selection: ?fields=id,name,email
export function parseFields(fieldsParam: string | undefined, allowed: string[]) {
if (!fieldsParam) return allowed;
const requested = fieldsParam.split(",").map(f => f.trim());
return requested.filter(f => allowed.includes(f));
}
// Advanced filtering: ?filter[status]=active&filter[price][gte]=100
export const filterSchema = z.record(z.union([
z.string(),
z.record(z.string())
]));
export function buildFilters(filters: z.infer<typeof filterSchema>) {
const conditions = [];
for (const [field, value] of Object.entries(filters)) {
if (typeof value === "string") {
conditions.push({ field, operator: "eq", value });
} else {
for (const [op, val] of Object.entries(value)) {
conditions.push({ field, operator: op, value: val });
}
}
}
return conditions;
}
// Sorting: ?sort=-createdAt,name (minus for desc)
export function parseSort(sortParam: string | undefined) {
if (!sortParam) return [];
return sortParam.split(",").map(field => {
const desc = field.startsWith("-");
return {
field: desc ? field.slice(1) : field,
order: desc ? "desc" : "asc"
};
});
}
```
## API Versioning
```typescript
// routes/api/index.ts
import { Hono } from "hono";
import v1Users from "./v1/users";
import v2Users from "./v2/users";
const app = new Hono();
// URL path versioning
app.route("/v1/users", v1Users);
app.route("/v2/users", v2Users);
// Header-based versioning alternative
app.use("/*", async (c, next) => {
const version = c.req.header("API-Version") || "1";
c.set("apiVersion", version);
await next();
});
export default app;
```
## Best Practices
1. **Use consistent naming conventions** (plural nouns, kebab-case)
2. **Version your API** from the start
3. **Return proper HTTP status codes**
4. **Use HATEOAS links** for discoverability
5. **Implement pagination** for list endpoints
6. **Provide filtering, sorting, and field selection**
7. **Document with OpenAPI/Swagger**
Google Antigravity helps design consistent APIs and generates client SDKs automatically.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.