OpenAPI ile API Dokümantasyonunu Otomatikleştir

API geliştirirken dokümantasyon yazması çoğu zaman sıkıcı ve hata yapmaya açık bir iş haline gelir. El ile tuttuğun dokümantasyon kodla senkron kalamaz, endpoint değişince güncellemeyi unutursun. OpenAPI spesifikasyonu bu sorunu çözer: API'nin yapısını JSON veya YAML dosyasında tanımlarsın, geri kalan otomatik olur.

OpenAPI (eski adıyla Swagger), RESTful API'leri standart bir formatta tanımlayan açık bir spesifikasyondur. Bir kez yazıp, ondan interaktif dokümantasyon, SDK, test araçları ve daha fazlasını üretebilirsin. Büyük şirketler (Google, Microsoft, Twitter) bunu kullanıyor; endüstri standardı haline geldi.

Bir YAML dosyası oluştur ve API'nin temel bilgilerini tanımla:

1openapi: 3.0.0
2info:
3title: Blog API
4version: 1.0.0
5description: Basit bir blog API'si
6servers:
8description: Üretim sunucusu
9paths:
10/posts:
11get:
12summary: Tüm yazıları listele
13responses:
14'200':
15description: Başarılı yanıt
16content:
17application/json:
18schema:
19type: array
20items:
21type: object
22properties:
23id:
24type: integer
25title:
26type: string
27content:
28type: string

Bu dosyayı `api.yaml` olarak kaydet.

Docker ile Swagger UI'yı çalıştırmak en hızlı yol:

1docker run -p 8080:8080 \
2-e SWAGGER_JSON=/api.yaml \
3-v $(pwd)/api.yaml:/api.yaml \
4swaggerapi/swagger-ui

Tarayıcıda `http://localhost:8080` aç. Interaktif, deneyebileceğin bir dokümantasyon sayfası göreceksin.

Reklam · TEST
AdSense Test ReklamıYazı arası (gönderi içi) · Yazı arası

Yazı oluşturma endpoint'ini ekle:

1post:
2summary: Yeni yazı oluştur
3requestBody:
4required: true
5content:
6application/json:
7schema:
8type: object
9properties:
10title:
11type: string
12content:
13type: string
14required:
15- title
16- content
17responses:
18'201':
19description: Yazı başarıyla oluşturuldu
20content:
21application/json:
22schema:
23type: object
24properties:
25id:
26type: integer
27title:
28type: string

Dosyayı kaydet; Swagger UI otomatik güncellenir.

Python FastAPI kullanıyorsan, OpenAPI otomatik oluşturulur:

1from fastapi import FastAPI
2
3app = FastAPI(
4title="Blog API",
5version="1.0.0"
6)
7
8@app.get("/posts")
9def get_posts():
10return [{"id": 1, "title": "İlk yazı"}]
11
12@app.post("/posts")
13def create_post(title: str, content: str):
14return {"id": 2, "title": title}

`uvicorn main:app --reload` ile çalıştır. `http://localhost:8000/docs` adresinde otomatik dokümantasyon görünür.

OpenAPI, dokümantasyon yazma zahmetini ortadan kaldırır. Bir kez tanımla, her yerde kullan.

Reklam · TEST
AdSense Test ReklamıGönderi altı · Görüntülü
konu hakkında tepkinizi verebilirsiniz