REST i GraphQL API w Claude Code
Twój zespół produktowy właśnie określił zakres nowej integracji. Partner potrzebuje REST API z dwunastoma endpointami, uwierzytelnianiem OAuth2, limitowaniem zapytań i dostarczaniem webhooków. Potrzebujesz tego gotowego do produkcji w dwa tygodnie. Tradycyjne podejście oznacza trzy dni szablonowego kodu, zanim napiszesz choć jedną linijkę logiki biznesowej — szkielety tras, schematy walidacji, handlery błędów, middleware uwierzytelniania i specyfikacja OpenAPI, której partner użyje do integracji.
Claude Code kompresuje to scaffoldowanie do jednej sesji. Opisujesz projekt API, Claude generuje trasy z walidacją i obsługą błędów pasującymi do twoich istniejących wzorców, a ty testujesz endpointy curlem prosto z tego samego terminala. Kluczem jest umiejętność kierowania generowaniem tak, aby otrzymać kod jakości produkcyjnej zamiast demo.
Czego się nauczysz
Dział zatytułowany „Czego się nauczysz”- Workflow do projektowania i implementacji API całkowicie z terminala
- Prompty generujące endpointy z odpowiednią walidacją, uwierzytelnianiem i obsługą błędów
- Technika testowania curlem inline do szybkiego rozwoju API
- Wzorce generowania specyfikacji OpenAPI z handlerów tras
Workflow tworzenia API
Dział zatytułowany „Workflow tworzenia API”-
Najpierw zaprojektuj kontrakt API
Zanim napiszesz jakikolwiek kod, poproś Claude o stworzenie dokumentu projektowego API. Pozwala to wychwycić problemy projektowe, zanim zaangażujesz się w implementację.
-
Przejrzyj projekt przed implementacją
Przeczytaj projekt API. Sprawdź, czy zasoby są poprawne, nazewnictwo jest spójne, a kody błędów mają sens. O wiele taniej jest zmienić dokument projektowy niż refaktoryzować zaimplementowany kod.
-
Zaimplementuj trasy pasujące do istniejących wzorców
Read the existing route handlers in src/routes/ to learn ourpatterns. Then implement the partner API routes following thesame structure:- Same middleware chain (auth, rate limit, validation)- Same error response format- Same logging approach- Same test patternsStart with the products endpoints. I'll review before youmove to orders. -
Testuj inline curlem
Tu workflow natywny dla terminala naprawdę błyszczy. Nie potrzebujesz Postmana ani osobnego narzędzia — testuj prosto z sesji Claude.
Start the dev server, then test the products endpoint:curl -X GET http://localhost:3000/api/v1/products \-H "Authorization: Bearer test-token" \-H "Content-Type: application/json"Show me the response. Then test with invalid auth,missing parameters, and an empty result set. -
Wygeneruj specyfikację OpenAPI
Now that the routes are implemented and tested, generate anOpenAPI 3.0 spec from the actual route handlers and Zod schemas.Save it to docs/partner-api.yaml.
Implementacja endpointów REST
Dział zatytułowany „Implementacja endpointów REST”Podejście walidacja-najpierw
Dział zatytułowany „Podejście walidacja-najpierw”Dobre API waliduje dane wejściowe przed czymkolwiek innym. Claude potrafi generować schematy Zod (lub równoważne) bezpośrednio z twojego projektu API.
Create Zod schemas for the partner API:
1. ProductQuerySchema - validates query parameters for GET /products (category: string, minPrice: number, maxPrice: number, page: number, limit: number)
2. CreateOrderSchema - validates the POST /orders body (customerId: string, items: array of {productId, quantity}, shippingAddress: object, notes: optional string)
3. WebhookConfigSchema - validates POST /webhooks body (url: valid URL, events: array of event types, secret: string)
Put them in src/schemas/partner.schema.ts following the patternsin our existing schema files.Spójna obsługa błędów
Dział zatytułowany „Spójna obsługa błędów”Uwierzytelnianie i autoryzacja
Dział zatytułowany „Uwierzytelnianie i autoryzacja”Implement OAuth2 client credentials authentication for thepartner API. Read our existing auth middleware insrc/middleware/auth.ts for patterns.
The partner auth flow:1. Partner requests token: POST /oauth/token with client_id and client_secret2. We return a JWT with scopes: products:read, orders:write, webhooks:manage3. Each endpoint checks the required scope4. Tokens expire after 1 hour
Create the middleware and apply it to the partner routes.Include tests that verify:- Valid token with correct scope passes- Valid token with wrong scope gets 403- Expired token gets 401- Missing token gets 401Implementacja GraphQL API
Dział zatytułowany „Implementacja GraphQL API”W projektach korzystających z GraphQL, Claude generuje schematy, resolvery i wzorce DataLoader potrzebne do unikania zapytań N+1.
We're adding a GraphQL API alongside our REST endpoints.Read the existing REST route handlers and database models.
Generate:1. GraphQL schema (SDL) with types matching our models2. Resolvers that call our existing service layer3. DataLoaders for User, Product, and Order to prevent N+14. Authentication context that integrates with our JWT auth
Use Apollo Server and follow the patterns from the GraphQLexample in our docs. Include connection types for paginatedlists (Relay cursor-based pagination).Zapobieganie zapytaniom N+1
Dział zatytułowany „Zapobieganie zapytaniom N+1”Our GraphQL API has N+1 problems. When querying orders,each order loads its user individually. Read the resolvercode in src/graphql/resolvers/.
Create DataLoaders for:1. UserLoader - batch load users by ID2. ProductLoader - batch load products by ID3. OrderItemsLoader - batch load order items by order ID
Wire them into the Apollo context. Show me the before/afterquery count for a query that fetches 20 orders with theirusers and items.Testowanie API z terminala
Dział zatytułowany „Testowanie API z terminala”Testowanie inline curlem
Dział zatytułowany „Testowanie inline curlem”Najszybszy sposób na testowanie API podczas developmentu to curl z tej samej sesji terminala, w której działa Claude.
Test the complete order creation flow:
1. Create a product:curl -X POST http://localhost:3000/api/v1/products \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name": "Widget", "price": 29.99, "category": "tools"}'
2. Create an order using the product ID from step 1:curl -X POST http://localhost:3000/api/v1/orders \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"customerId": "cust-123", "items": [{"productId": "PRODUCT_ID", "quantity": 2}]}'
3. Verify the order was created:curl -X GET http://localhost:3000/api/v1/orders/ORDER_ID \ -H "Authorization: Bearer $TOKEN"
Show me each response.Automatyczne generowanie testów API
Dział zatytułowany „Automatyczne generowanie testów API”Generate API integration tests for the partner endpoints.Use supertest (or the test client for our framework).Follow the test patterns in tests/routes/.
For each endpoint, test:- Successful request with valid input- Validation error with invalid input- Authentication required (no token)- Authorization denied (wrong scope)- Not found (invalid ID)- Conflict (duplicate creation)- Rate limit exceeded
Include a test helper that creates an authenticated test clientwith partner credentials.Limitowanie zapytań i paginacja
Dział zatytułowany „Limitowanie zapytań i paginacja”Implementacja limitowania zapytań
Dział zatytułowany „Implementacja limitowania zapytań”Add rate limiting to the partner API. Read our existing ratelimiter in src/middleware/rateLimit.ts.
Configuration:- Standard tier: 100 requests per minute per API key- Elevated tier: 1000 requests per minute per API key- Include X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers on every response- Return 429 with Retry-After header when exceeded
The tier is determined by the partner's plan stored in thedatabase. Cache the plan lookup in Redis with a 5-minute TTL.Paginacja oparta na kursorze
Dział zatytułowany „Paginacja oparta na kursorze”Implement cursor-based pagination for all list endpoints.Read our existing pagination helper in src/lib/pagination.ts.
The response format should be:{ "data": [...], "pagination": { "cursor": "encoded-cursor", "hasMore": true, "totalCount": 1234 }}
The cursor encodes the sort field and ID for consistentordering. Support both forward and backward pagination.Add tests that verify pagination works correctly withfilters applied.Implementacja webhooków
Dział zatytułowany „Implementacja webhooków”Implement webhook delivery for order status changes.
1. Partners register webhooks: POST /webhooks - URL, events to subscribe, signing secret
2. When an order status changes, queue webhook deliveries to all subscribers of that event
3. Webhook payload format: { "event": "order.status_changed", "data": { order }, "timestamp": "ISO" }
4. Sign each payload with HMAC-SHA256 using the partner's secret Include the signature in X-Webhook-Signature header
5. Retry failed deliveries: 3 attempts with exponential backoff (30s, 5min, 30min)
6. Log all delivery attempts for debugging
Follow our existing job queue patterns in src/jobs/.Include tests that verify signing, retry behavior, andthe delivery endpoint receiving correct payloads.Gdy coś idzie nie tak
Dział zatytułowany „Gdy coś idzie nie tak”Wygenerowane endpointy mają niespójne formaty odpowiedzi. Claude czasami używa różnych kształtów błędów w różnych endpointach. Zdefiniuj format raz i egzekwuj go: “All error responses must use the ErrorResponse type defined in src/types/api.ts. Do not create ad-hoc error objects.”
Walidacja jest zbyt luźna lub zbyt ścisła. Przejrzyj schematy Zod wygenerowane przez Claude pod kątem twoich rzeczywistych danych. Częste problemy: pola tekstowe bez maksymalnej długości, pola liczbowe bez rozsądnych granic, pola opcjonalne, które powinny być wymagane. Powiedz Claude: “For every field in the schema, add reasonable constraints. Strings need maxLength, numbers need min/max, arrays need maxItems.”
Middleware uwierzytelniania jest stosowany niespójnie. Niektóre endpointy wymagają uwierzytelniania, inne nie. Ustal konwencję: “All routes under /api/v1/partner/ require the partnerAuth middleware. Health checks and the OAuth token endpoint are the only exceptions. Verify this by listing all routes and their middleware.”
API działa dobrze w testach, ale wolno na produkcji. Testowa baza danych jest mała. Dodaj test wydajnościowy: “Generate a test that creates 10,000 products, then benchmarks the list endpoint with various filter combinations. Show me response times and query counts.”
Specyfikacja OpenAPI rozmija się z implementacją. Generuj specyfikację z kodu, nie odwrotnie. Dodaj sprawdzenie w CI: “Compare the OpenAPI spec with the actual route handlers. Fail the build if they disagree.”
Co dalej
Dział zatytułowany „Co dalej”Twoje API jest zaimplementowane z odpowiednią walidacją, uwierzytelnianiem i obsługą błędów. Teraz upewnij się, że warstwa bazy danych pod spodem jest zaprojektowana pod zapytania, które twoje API faktycznie wykonuje.