agentleFS
joaoguirunasjoaoguirunas/team-os/.claude/skills/dev-api-design/SKILL.md

dev-api-design

Skill6 starsChanged 25 days agoMITView on GitHub

Design de APIs para software complexo — REST, tRPC, contratos, versionamento e error responses padronizadas.

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    PUT e DELETE sempre idempotentes

    line 139

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

API Design — Software Complexo

REST — Nomenclatura

GET    /users              → listar
GET    /users/:id          → buscar por ID
POST   /users              → criar
PUT    /users/:id          → substituir completo
PATCH  /users/:id          → atualizar parcial
DELETE /users/:id          → remover

# Ações não-CRUD (POST + verbo explícito)
POST   /users/:id/deactivate
POST   /auth/refresh
POST   /payments/:id/refund

Regras: plural sempre (/users), nunca verbos em recursos, máx 2 níveis de aninhamento.

Responses

Sucesso

{
  "data": { "id": "usr_123", "email": "user@example.com" },
  "meta": { "requestId": "req_abc" }
}

Lista paginada

{
  "data": [...],
  "pagination": { "page": 1, "perPage": 20, "total": 150, "hasNext": true }
}

Erro — padrão obrigatório

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request data",
    "details": [{ "field": "email", "message": "Must be a valid email" }],
    "requestId": "req_abc"
  }
}

requestId obrigatório em todas as respostas — sucesso e erro. Gerado no middleware de entrada e propagado pelo sistema. Usar o mesmo requestId nos logs (ver dev-security-patterns) para rastrear requests end-to-end.

Nunca expor: stack traces, mensagens de banco, lógica interna.

HTTP Status + Códigos de Erro

HTTPCodeQuando
200—GET, PATCH, PUT ok
201—POST criou recurso
204—DELETE ou ação sem body
400VALIDATION_ERRORInput inválido
401UNAUTHORIZEDNão autenticado
403FORBIDDENSem permissão
404NOT_FOUNDNão existe
409CONFLICTEstado conflitante
429RATE_LIMITEDRate limit
500INTERNAL_ERRORErro interno

requestId — Geração e Propagação

// Middleware de entrada — gerar requestId único
app.use((req, res, next) => {
  req.requestId = req.headers['x-request-id'] as string
    ?? `req_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`
  res.setHeader('x-request-id', req.requestId)
  next()
})

// Passar requestId para logs e serviços downstream
logger.info('Request received', { requestId: req.requestId, path: req.path })

tRPC (TypeScript full-stack)

export const userRouter = router({
  getById: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input, ctx }) => {
      return ctx.db.user.findUnique({ where: { id: input.id } })
    }),
  create: protectedProcedure
    .input(createUserSchema)
    .mutation(async ({ input, ctx }) => {
      return ctx.db.user.create({ data: input })
    }),
})

Usar tRPC: Next.js + TypeScript, type-safety end-to-end. Usar REST: API pública para terceiros ou linguagens mistas.

Versionamento

URL path: /api/v1/users → /api/v2/users

  • Bump de versão apenas em breaking changes
  • Manter versão anterior 3+ meses
  • Header Sunset: {date} na versão sendo descontinuada

Contrato de API

Documentar em docs/api/{resource}.md ao criar/modificar endpoint:

## POST /users
**Auth:** Bearer token | **Rate limit:** 10/min

### Request
\`{ "email": "string", "name": "string" }\`

### Response 201
\`{ "data": { "id": "string" }, "meta": { "requestId": "string" } }\`

### Erros: 409 CONFLICT (email duplicado), 400 VALIDATION_ERROR

Regras absolutas

  • IDs opacos: usr_abc123, nunca 123
  • PUT e DELETE sempre idempotentes
  • Rate limiting em todos os endpoints públicos
  • Timeout explícito em todas as chamadas a externos
  • requestId em todas as respostas — sucesso e erro, sem exceção
  • Breaking change = bump de versão, sem exceção

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.