RESTful API Tasarım Prensipleri

Yazılım 📖 2 dk okuma
#web#design#javascript

İyi tasarlanmış bir API, uygulamanızın başarısında kritik rol oynar.

RESTful Prensipler

1. Tutarlı URL Yapısı

✅ GET    /api/users          # Tüm kullanıcılar
✅ GET    /api/users/:id      # Belirli kullanıcı
✅ POST   /api/users          # Yeni kullanıcı
✅ PUT    /api/users/:id      # Kullanıcı güncelle
✅ DELETE /api/users/:id      # Kullanıcı sil

❌ /api/getUsers
❌ /api/user-create
❌ /api/deleteUserById

2. HTTP Status Kodları

Doğru status kodlarını kullanın:

// Başarılı işlemler
200 OK           // Başarılı GET, PUT
201 Created      // Başarılı POST
204 No Content   // Başarılı DELETE

// Client hataları
400 Bad Request      // Geçersiz istek
401 Unauthorized     // Kimlik doğrulama gerekli
403 Forbidden        // Yetkisiz erişim
404 Not Found        // Kaynak bulunamadı
422 Unprocessable    // Validation hatası

// Server hataları
500 Internal Server Error
503 Service Unavailable

3. Versiyonlama

API versiyonunu URL’de belirtin:

/api/v1/users
/api/v2/users

4. Pagination

Büyük veri setleri için pagination:

GET /api/users?page=2&limit=20

// Response
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 150,
    "pages": 8
  }
}

5. Filtering ve Sorting

GET /api/users?status=active&sort=-createdAt
GET /api/products?category=electronics&minPrice=100

Error Handling

Tutarlı error formatı:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ]
  }
}

Documentation

Swagger/OpenAPI ile API dokümantasyonu:

openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: Successful response

İyi tasarlanmış API, geliştiricilerin işini kolaylaştırır ve hataları azaltır!