Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
API Design Patterns

API Design Patterns

Design clean, consistent, and developer-friendly APIs with Google Antigravity

apirestdesign-patternshono
by antigravity-team
⭐0Stars
.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.

When to Use This Prompt

This api prompt is ideal for developers working on:

  • api applications requiring modern best practices and optimal performance
  • Projects that need production-ready api code with proper error handling
  • Teams looking to standardize their api development workflow
  • Developers wanting to learn industry-standard api patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the api code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this api prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...