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.02info:3title: Blog API4version: 1.0.05description: Basit bir blog API'si6servers:7- url: https://api.example.com8description: Üretim sunucusu9paths:10/posts:11get:12summary: Tüm yazıları listele13responses:14'200':15description: Başarılı yanıt16content:17application/json:18schema:19type: array20items:21type: object22properties:23id:24type: integer25title:26type: string27content:28type: stringBu 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-uiTarayıcıda `http://localhost:8080` aç. Interaktif, deneyebileceğin bir dokümantasyon sayfası göreceksin.
Yazı oluşturma endpoint'ini ekle:
1post:2summary: Yeni yazı oluştur3requestBody:4required: true5content:6application/json:7schema:8type: object9properties:10title:11type: string12content:13type: string14required:15- title16- content17responses:18'201':19description: Yazı başarıyla oluşturuldu20content:21application/json:22schema:23type: object24properties:25id:26type: integer27title:28type: stringDosyayı kaydet; Swagger UI otomatik güncellenir.
Python FastAPI kullanıyorsan, OpenAPI otomatik oluşturulur:
1from fastapi import FastAPI23app = FastAPI(4title="Blog API",5version="1.0.0"6)78@app.get("/posts")9def get_posts():10return [{"id": 1, "title": "İlk yazı"}]1112@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.
0 yorum