İçeriğe geç
Kodlama ve Yazılım İleri

AI ile API Tasarımı: REST, GraphQL, gRPC Best Practices

AI ile API tasarım: REST, GraphQL, gRPC. Versiyonlama, auth, rate limit, error handling, OpenAPI.

YZ
Paylaş:
API endpoint diyagramı

API tasarımı = birinci izlenim + uzun vade evrim. Yanlış başlangıç = 5 yıl ağrı. AI ile yapısal hızlı.

REST API Tasarımı

Görev: Aşağıdaki domain için REST API:

Domain: Blog platform
- User, Post, Comment, Tag

Çıktı:
1. Resource URL design
2. HTTP method mapping
3. Status code conventions
4. Request/response example
5. Pagination (cursor / offset)
6. Filtering / sorting / search
7. Versioning strategy
8. Auth (JWT vs OAuth)
9. Rate limit
10. OpenAPI spec

Örnek output:

GET    /v1/posts                  # List (paginated)
GET    /v1/posts/:id              # Detail
POST   /v1/posts                  # Create
PATCH  /v1/posts/:id              # Update partial
PUT    /v1/posts/:id              # Replace
DELETE /v1/posts/:id              # Delete

GET    /v1/posts/:id/comments     # Nested
POST   /v1/posts/:id/comments

GET    /v1/posts?status=published&tag=ai&limit=20&cursor=...

URL Conventions

✅ İyi:

  • /users (plural)
  • /users/:id
  • /users/:id/posts (nested resource)
  • snake_case veya kebab-case
  • ?filter[status]=active

❌ Kötü:

  • /getUser (verb)
  • /user (singular)
  • /post/:id/getComment (mixed)
  • Mixed case /userPosts

HTTP Status Codes

CodeMeaning
200 OKSuccess
201 CreatedPOST success
204 No ContentDELETE, PUT success
400 Bad RequestClient error (validation)
401 UnauthorizedNot authenticated
403 ForbiddenAuthenticated but no permission
404 Not FoundResource doesn’t exist
409 ConflictState conflict (duplicate)
422 UnprocessableSemantic error
429 Too ManyRate limit
500 Server ErrorServer bug
503 Service UnavailableMaintenance / overload

Error Response

Tutarlı format:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Email is invalid",
    "details": [
      {
        "field": "email",
        "issue": "invalid_format"
      }
    ],
    "request_id": "req_abc123",
    "documentation_url": "https://docs.api.com/errors/VALIDATION_ERROR"
  }
}
"Aşağıdaki error response için spec:

API: Payment

Errors:
- PAYMENT_FAILED
- INSUFFICIENT_FUNDS
- CARD_EXPIRED
- 3DS_REQUIRED
- RATE_LIMITED

Her birinin:
- HTTP status
- Code
- Message (Türkçe + English)
- Action (retry / fix / contact support)
- Stripe / Iyzico mapping (örnek)
"

Pagination

"Pagination strategy:

Cursor-based:
GET /posts?limit=20&cursor=abc

Response:
{
  "data": [...],
  "pagination": {
    "next_cursor": "def",
    "has_more": true
  }
}

Avantaj: stable (insert sırasında shift yok)
Dezavantaj: random access yok

vs Offset-based:
GET /posts?page=2&limit=20

Avantaj: page number göster
Dezavantaj: large offset yavaş

Use case match:
- Feed (Twitter) → cursor
- Search results → offset
- Admin panel → offset"

Authentication

"Auth strategy karşılaştırma:

1. API Key (simple)
   - GET /users -H "Authorization: Bearer sk_..."
   - Pros: simple, server-to-server
   - Cons: revoke complex, no expiry

2. JWT (stateless)
   - Token: header.payload.signature
   - Pros: stateless, scale-friendly
   - Cons: revoke complex, size

3. OAuth 2.0 (user delegation)
   - Authorization code flow
   - Pros: user consent, granular scope
   - Cons: complex setup

4. Session (stateful)
   - Cookie + DB session
   - Pros: easy revoke
   - Cons: scale (sticky session)

Use case:
- SaaS B2B → OAuth + JWT
- Public API → API key
- Internal microservice → mTLS
"

Rate Limiting

"Rate limit design:

Tier:
- Free: 100 req/hour
- Pro: 10000 req/hour
- Enterprise: custom

Algorithm:
- Token bucket (Stripe)
- Sliding window (Twitter)
- Leaky bucket (network)

Response (429):
{
  "error": "RATE_LIMITED",
  "retry_after": 60
}

Headers:
- X-RateLimit-Limit: 1000
- X-RateLimit-Remaining: 999
- X-RateLimit-Reset: 1234567890

Distributed: Redis (atomic INCR + TTL).
"

Versioning

"API v1 → v2 migration:

Breaking change: email field renamed to user_email

Strategy:
1. v2 launch (both work)
2. Deprecation header in v1 response
3. 6 month sunset notice
4. Email customers
5. Dashboard usage metrics
6. v1 sunset

Header approach:
Sunset: Sat, 30 Jun 2026 00:00:00 GMT
Deprecation: true
Link: <https://api/v2/users>; rel="successor-version"
"

GraphQL Schema

"Aşağıdaki REST API → GraphQL:

REST:
- GET /users
- GET /users/:id (with posts)
- GET /posts/:id (with comments)

GraphQL:
type Query {
  users(first: Int, after: String): UserConnection!
  user(id: ID!): User
  post(id: ID!): Post
}

type User {
  id: ID!
  name: String!
  email: String!
  posts(first: Int): [Post!]!
}

type Post {
  id: ID!
  title: String!
  author: User!
  comments(first: Int): [Comment!]!
}

# Mutations
type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
}

# Subscriptions
type Subscription {
  postAdded: Post!
  commentAdded(postId: ID!): Comment!
}
"

gRPC Service

"gRPC service tanımı:

syntax = "proto3";

service UserService {
  rpc GetUser (GetUserRequest) returns (User);
  rpc ListUsers (ListUsersRequest) returns (ListUsersResponse);
  rpc CreateUser (CreateUserRequest) returns (User);
  rpc UpdateUser (UpdateUserRequest) returns (User);
  rpc StreamUsers (StreamUsersRequest) returns (stream User);
}

message User {
  string id = 1;
  string name = 2;
  string email = 3;
  google.protobuf.Timestamp created_at = 4;
}
"

OpenAPI 3.1

openapi: 3.1.0
info:
  title: Blog API
  version: 1.0.0
  description: ...

paths:
  /v1/posts:
    get:
      summary: List posts
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PostList'

components:
  schemas:
    Post:
      type: object
      required: [id, title]
      properties:
        id:
          type: string
        title:
          type: string
"OpenAPI'dan otomatik üret:
- Postman collection
- Client SDK (TypeScript, Python)
- Mock server
- Documentation site
- Integration tests
- Gateway config (Kong, AWS API Gateway)
"

Webhook Tasarımı

"Webhook spec:

Event: payment.success

Payload:
{
  "id": "evt_abc",
  "type": "payment.success",
  "created": 1234567890,
  "data": {
    "payment_id": "pay_xyz",
    "amount": 100,
    "currency": "TRY"
  }
}

Security:
- HMAC signature header
- Retry logic (exponential backoff)
- Idempotency (event ID)
- Failed delivery alerting
- Replay endpoint
"

Documentation

Detay: API Dokümantasyon

"API docs structure:

1. Quickstart (5 min get started)
2. Authentication
3. Pagination
4. Errors
5. Webhooks
6. Reference (per endpoint)
7. SDK / libraries
8. Changelog
9. Status page
10. Support / community"

Yaygın Hatalar

  1. Plural vs singular karışık: /users ve /post
  2. Verb URL: /createUser yerine POST /users
  3. Status code 200 her şey: Use 4xx, 5xx
  4. Error message generic: “Something wrong” → debug zor
  5. Versioning skip: 2 yıl sonra breaking
  6. No rate limit: DDoS açık
  7. No idempotency: Webhook duplicate

Sonraki Adımlar

Özet

API tasarım = uzun vade investment. REST (public), GraphQL (complex client), gRPC (microservice). OpenAPI mandatory. AI ile yapısal hızlı, spec-first development. Anahtar: tutarlılık + versiyonlama + error handling.

Paylaş:

Yapay zeka dünyasından haberdar olun

Haftalık özet bültenimize abone olun, en yeni rehberler ve araç incelemeleri direkt e-postanıza gelsin.

İstediğiniz zaman abonelikten çıkabilirsiniz.