Ana Sayfa / Blog / OpenAPI/Swagger ile doc-first development disiplini

OpenAPI/Swagger ile doc-first development disiplini

API geliştirirken doc'u sonradan yazmak anti-pattern. OpenAPI spec'ini önce yazmanın 4 pratik faydası.

API geliştirme workflow’unda tipik pattern şu: backend kodla, kod biraz stabilize oldu sonra doc yaz, doc kodla senkron değil, kimse maintain etmiyor.

Doc-first approach: önce OpenAPI spec’i yaz, spec’i source of truth kabul et, kodu ve doc’u spec’ten generate et veya generate edilmezse manually keep in sync. Bu disiplinle çalıştığım projelerde sonuç çok daha iyi oldu.

Bu yazıda doc-first workflow’un pratik faydalarını ve nasıl kurduğunu anlatacağım.

OpenAPI nedir, tekrar hatırlayalım

OpenAPI (eskiden Swagger) REST API’leri tanımlayan bir standart. YAML veya JSON format’ta. Endpoint’ler, request/response schema’ları, authentication, error’lar hepsi tanımlanıyor.

Basic example:

openapi: 3.0.3
info:
  title: My API
  version: 1.0.0
paths:
  /users/{id}:
    get:
      summary: Get user by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        email: { type: string }

Bu spec okunabilir, version controllable, validation için machine-parseable.

Doc-first benefit 1: design review önce, implementation sonra

Traditional flow: backend endpoint implementation yapıyor, sonra frontend görüyor, “bu format yanlış” diye feedback veriyor, backend değiştiriyor. 2-3 iteration.

Doc-first: OpenAPI spec’i PR’da review ediyorsun. Frontend developer, backend developer, product manager hepsi review’a katılıyor. Spec onaylanınca implementation başlıyor.

Bu sayede:
– Yanlış field naming erken yakalanıyor
– Missing edge case’ler (pagination, filtering) spec’te görülüyor
– Frontend development backend’le paralel başlıyor (mock server’la)

Benim projelerimde spec review 1-2 saat. Bunu yapmamak ise hafta harcıyor.

Doc-first benefit 2: code generation

OpenAPI spec’ten otomatik kod generate edebilirsin:

Backend models:
– openapi-generator-cli ile Go/Python/Node.js struct’lar.
– Spec değişirse structs auto-update.

API client libraries:
– Frontend için TypeScript client (type-safe fetch calls).
– iOS için Swift package.
– Android için Kotlin library.
– Her platform’a kendi native client.

Example:

openapi-generator-cli generate 
  -i openapi.yaml 
  -g typescript-axios 
  -o ./frontend/src/api-client

Frontend developer typed fonksiyonlar alıyor:

const user = await api.users.getUser({ id: '123' });
// user: User type

Hand-written fetch call’ları yerine auto-generated, type-safe client.

Doc-first benefit 3: mock server (parallel development)

OpenAPI spec’ten mock server generate ediyorsun. Frontend backend’in implement edilmesini beklemiyor.

Tool’lar:
Prism: prism mock openapi.yaml tek komut, mock server hazır.
Stoplight Prism: CLI + cloud versions.
MockAPI: SaaS, web UI ile mock.

Frontend developer:

fetch('http://localhost:4010/users/123')
// Mock response: example data from spec

Backend developer paralelde actual endpoint’i yazıyor. Ikisi aynı spec’e göre çalıştığı için integration noktasında uyumsuzluk minimum.

Doc-first benefit 4: documentation always current

Major pain point: doc kod’la senkron değil. 6 ay sonra “docs’u güncellemedik” diye farkediyorsun.

Doc-first approach’ta:

  • Spec code repo’suyla aynı yerde
  • Every PR’da spec de update oluyor (veya reviewer talep ediyor)
  • Spec’ten generated client libs her build’de re-generate, stale code çalışmıyor
  • Swagger UI / Redoc spec’ten realtime render

Doc’un “bir günkü snapshot’ı” değil, gerçek zamanlı API surface.

Tool ecosystem

OpenAPI tool ecosystem güçlü:

Spec writing:
– Stoplight Studio: visual editor
– Swagger Editor: web-based
– VS Code OpenAPI extension

Rendering:
– Swagger UI: classic interactive doc
– Redoc: modern, cleaner
– Stoplight Elements: embedable component

Validation:
– Spectral: lint rules for OpenAPI spec
– openapi-validator: schema conformance

Testing:
– Dredd: spec ile actual API karşılaştırma (contract testing)
– Postman: spec import, test collections

Mock:
– Prism: CLI mock server
– MockServer: advanced mock with recording

Practical workflow

Benim kullandığım iş akışı:

1. Design phase (1-2 gün):
– Feature PM ile speccing: endpoint’ler, user journey
– İlk OpenAPI draft yazıyorum
– PR olarak açıyorum, title: “[SPEC] User Management API v1”

2. Review phase (1-2 gün):
– Frontend + backend + QA review
– Schema field’ları tartışılıyor
– Edge case’ler ekleniyor (error responses, pagination)
– PR merge

3. Parallel implementation (1-2 hafta):
– Backend actual endpoint implement ediyor
– Frontend auto-generated TypeScript client kullanarak implement ediyor
– QA postman collection’ını spec’ten generate ediyor

4. Integration (1-2 gün):
– Backend endpoint’i frontend’den test ediliyor
– Contract testing (Dredd) spec ile implementation uyumunu check ediyor
– Issue varsa spec vs code tartışması (genelde spec kazanıyor çünkü review edildi)

5. Release:
– Swagger UI automatically generated
– Public API documentation site
– Client libraries versioned package’lara publish

Bu workflow 3-5 hafta’lık feature için tipik olarak 1 hafta ekliyor early design phase’e. Ama integration bug’larını 2-3 hafta azaltıyor. Net değer: %30 hız.

Common antipatterns

1. Spec’i kodan sonra yazmak. Bu aslında doc-first DEĞİL. Generic documentation burada kazancı daha düşük.

2. Spec’i update etmeden code değiştirmek. 1-2 ay sonra spec stale, kimse güvenmiyor. Team discipline gerekiyor.

3. Spec çok simple. Sadece happy path. Error response’ları, edge case’leri eksik. Spec’te her response code belirtilmeli.

4. Tooling overload. 10 farklı tool kullanıyorsun, hiçbirini tam setup etmeden. Minimum: Swagger UI (docs) + Prism (mock) + openapi-generator (client libs).

Migration: existing API’den doc-first’e

Mevcut bir API’ı retroactively OpenAPI’ye taşımak büyük iş. Strategy:

Phase 1: Son version’u spec’le. Tüm endpoint’leri dokümante et, çalışmayan test yoksa implementation’ı spec’e uygunluk için güncelle.

Phase 2: Yeni feature’lar doc-first.

Phase 3: Legacy endpoint’ler kademeli spec’e.

Bu 6-12 aylık bir çalışma ama iyi investment. Large API’ları maintain etmeyi kolaylaştırıyor.

OpenAPI 3.0 vs 3.1

Version seçimi:

  • OpenAPI 3.0: Mature, tool support geniş. Most common.
  • OpenAPI 3.1: JSON Schema Draft 2020 uyumlu, better schema features.

Yeni projede OpenAPI 3.1 yaz. Mevcut projelerde 3.0 kalabilir.

Security in OpenAPI

Auth mekanizmaları spec’te:

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

paths:
  /users:
    get:
      security:
        - bearerAuth: []
      # ...

Her endpoint’in security requirement’ı spec’te. Swagger UI’da “Authorize” butonu interactive test için.

Monorepo vs split

Spec nereye konsun?

Single repo (monorepo): Backend repo’sunda openapi.yaml. Client lib’leri monorepo’da ayrı dizinde.

Spec repo: Ayrı bir repo sadece API spec için. Backend ve client’lar bu spec’i consume ediyor.

Small team için monorepo kolay. Multi-team enterprise’da spec repo ayrı disciplin olabiliyor.

Sonuç

Doc-first API development discipline-intensive ama büyük değer sağlıyor. Design review erken, frontend parallel çalışıyor, client lib’leri auto-generated, documentation always current.

OpenAPI ecosystem mature. İlk setup 1-2 haftalık iş. Ondan sonra her yeni API feature için 2-3 saat spec yazmak, ama 2-3 hafta integration bug’ı önlüyor. ROI positif.

Küçük başla: tek endpoint spec’le, Swagger UI render et, review yap. Pozitif geribildirim alırsan tüm API’ya yay.

Bu konuda bir projeniz mi var?

Kısa bir özet bırakın, 24 saat içinde size dönüş yapayım.

İletişime Geç