Saltar al contenido
Skillpedia
APIs y servidores (backend)107 mil · #761

api-and-interface-design

Qué hace

Esta guía ayuda a crear interfaces (como las API o los contratos entre partes de un programa) que sean fáciles de usar y difíciles de usar mal. Enseña a definir de forma clara y estable cómo se comunican distintas partes del software.

Cuándo usarla

  • ✓Al crear nuevas conexiones entre programas (API).
  • ✓Cuando definas cómo deben comunicarse distintas partes del mismo programa.
  • ✓Al planificar cómo interactúa un programa con el usuario (interfaz gráfica).

Link de la skill

https://github.com/addyosmani/agent-skills/blob/main/skills/api-and-interface-design/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/addyosmani/agent-skills/blob/main/skills/api-and-interface-design/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Ayúdame a definir cómo un usuario puede crear una nueva tarea en un sistema, indicando el título y la descripción.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Funciona definiendo primero cómo debe ser la comunicación (el "contrato") antes de escribir el código. Así, todos entienden las reglas y se evitan sorpresas.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

API and Interface Design

Overview

Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another.

When to Use

  • Designing new API endpoints
  • Defining module boundaries or contracts between teams
  • Creating component prop interfaces
  • Establishing database schema that informs API shape
  • Changing existing public interfaces

Core Principles

Hyrum's Law

With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract.

This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications:

  • Be intentional about what you expose. Every observable behavior is a potential commitment.
  • Don't leak implementation details. If users can observe it, they will depend on it.
  • Plan for deprecation at design time. See deprecation-and-migration for how to safely remove things users depend on.
  • Tests are not enough. Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.

The One-Version Rule

Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork.

1. Contract First

Define the interface before implementing it. The contract is the spec — implementation follows.

// Define the contract first
interface TaskAPI {
  // Creates a task and returns the created task with server-generated fields
  createTask(input: CreateTaskInput): Promise<Task>;

  // Returns paginated tasks matching filters
  listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;

  // Returns a single task or throws NotFoundError
  getTask(id: string): Promise<Task>;

  // Partial update — only provided fields change
  updateTask(id: string, input: UpdateTaskInput): Promise<Task>;

  // Idempotent delete — succeeds even if already deleted
  deleteTask(id: string): Promise<void>;
}

2. Consistent Error Semantics

Pick one error strategy and use it everywhere:

// REST: HTTP status codes + structured error body
// Every error response follows the same shape
interface APIError {
  error: {
    code: string;        // Machine-readable: "VALIDATION_ERROR"
    message: string;     // Human-readable: "Email is required"
    details?: unknown;   // Additional context when helpful
  };
}

// Status code mapping
// 400 → Client sent invalid data
// 401 → Not authenticated
// 403 → Authenticated but not authorized
// 404 → Resource not found
// 409 → Conflict (duplicate, version mismatch)
// 422 → Validation failed (semantically invalid)
// 500 → Server error (never expose internal details)

Don't mix patterns. If some endpoints throw, others return null, and others return { error } — the consumer can't predict behavior.

3. Validate at Boundaries

Trust internal code. Validate at system edges where external input enters:

// Validate at the API boundary
app.post('/api/tasks', async (req, res) => {
  const result = CreateTaskSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(422).json({
      error: {
        code: 'VALIDATION_ERROR',
        message: 'Invalid task data',
        details: result.error.flatten(),
      },
    });
  }

  // After validation, internal code trusts the types
  const task = await taskService.create(result.data);
  return res.status(201).json(task);
});

Where validation belongs:

  • API route handlers (user input)
  • Form submission handlers (user input)
  • External service response parsing (third-party data -- always treat as untrusted)
  • Environment variable loading (configuration)

Third-party API responses are untrusted data. Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text.

Where validation does NOT belong:

…

Preguntas frecuentes

¿Qué es una API?

Una API es como la carta de un restaurante: define lo que puedes pedir (funciones) y cómo pedirlo (parámetros), sin necesidad de saber cómo prepara la cocina (el programa) el plato.

¿Por qué es importante "primero el contrato"?

Es como acordar las reglas de un juego antes de empezar a jugar. Si todos conocen las reglas (el contrato), el programa funciona mejor y se evitan conflictos.

¿Qué es la "Ley de Hyrum"?

Es la idea de que, si mucha gente usa algo, acaba dependiendo de todos sus detalles, incluso de sus "rarezas" o comportamientos inesperados. Por eso conviene tener cuidado con lo que se expone.

Detalles

Descripción original del autor

Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.

repo: addyosmani/agent-skills

Popularidad

Estrellas en GitHub
107 mil
Posición en el ranking
#761
Licencia
MIT
Actualizada
13/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas