پرش به محتویات

راهنمای Swagger/OpenAPI

معرفی

این مستندات بر اساس مشخصات OpenAPI 3.1.0 تولید شده‌اند. می‌توانید از ابزارهای Swagger برای تست و مستندسازی تعاملی استفاده کنید.

فایل OpenAPI

فایل OpenAPI اصلی در این پروژه موجود نیست (به درخواست کاربر)، اما می‌توانید از مستندات Markdown به عنوان مرجع استفاده کنید.

ابزارهای پیشنهادی

1. Swagger UI

برای نمایش تعاملی API:

# نصب Swagger UI
pip install swagger-ui-bundle

# یا استفاده از فایل HTML
# فایل swagger.html را ایجاد کنید

فایل swagger.html:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css">
</head>
<body>
    <div id="swagger-ui"></div>
    <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
    <script>
        SwaggerUIBundle({
            url: "openapi.json",
            dom_id: '#swagger-ui',
            deepLinking: true
        })
    </script>
</body>
</html>

2. Postman

برای تست API:

وارد کردن: 1. Open Postman 2. File → Import 3. انتخاب فایل OpenAPI یا ایجاد Collection جدید

ساختار Collection:

Exchange API
├── Auth
│   ├── Login
│   └── Refresh
├── User
│   ├── List Users
│   ├── Create User
│   └── Get User
├── Wallet
│   ├── List Wallets
│   ├── Deposit
│   └── Withdraw
└── Exchange
    ├── Symbols
    ├── Orders
    ├── Trades
    └── Market Data

3. Insomnia

مشابه Postman اما با رابط کاربری متفاوت.

تولید فایل OpenAPI

از مستندات Markdown

می‌توانید از ابزارهای زیر استفاده کنید:

# نصب
pip install mkdocs-swagger-ui-plugin

# یا
pip install mkdocs-openapi-plugin

نمونه فایل OpenAPI

اگر نیاز به فایل OpenAPI دارید:

{
  "openapi": "3.1.0",
  "info": {
    "title": "Exchange API",
    "version": "1.0.0",
    "description": "API بازار اسکناس همتا به همتا"
  },
  "servers": [
    {
      "url": "https://api.example.com",
      "description": "Production"
    }
  ],
  "paths": {
    "/api/exchange/v1/symbols": {
      "get": {
        "summary": "List Symbols",
        "security": [{"bearerAuth": []}],
        "parameters": [
          {
            "name": "offset",
            "in": "query",
            "schema": {"type": "integer", "default": 0}
          }
        ],
        "responses": {
          "200": {
            "description": "Success",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "items": {"type": "array"},
                    "total": {"type": "integer"}
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer"
      }
    }
  }
}

استفاده از مستندات فعلی

1. جستجو

از قابلیت جستجوی MkDocs استفاده کنید: - فشار دادن / یا کلیک روی آیکون جستجو - تایپ کلمه کلیدی - انتخاب نتیجه

2. ناوبری

ساختار منو: - خانه: صفحه اصلی - معرفی: کلیات سیستم - مبادی API: قراردادها و احراز هویت - منطق دامنه: گردش کار - رفرنس API: جزئیات هر اندپوینت - مثال‌ها: کدهای آماده

3. کپی کد

  • روی هر کد کلیک کنید
  • دکمه Copy فعال می‌شود
  • مستقیماً در terminal اجرا کنید

تست با cURL

مثال کامل

# 1. Login
export JWT_TOKEN=$(curl -s -X POST "https://api.example.com/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"client_id":"...","client_secret":"..."}' | jq -r '.access_token')

# 2. Get symbols
curl -X GET "https://api.example.com/api/exchange/v1/symbols" \
  -H "Authorization: Bearer $JWT_TOKEN"

# 3. Get ticker
curl -X GET "https://api.example.com/api/exchange/v1/tickers/BTC-IRR"

# 4. Create order
curl -X POST "https://api.example.com/api/exchange/v1/orders" \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -d '{"symbol":"BTC-IRR","side":"buy","type":"limit","price":"1000000000","quantity":"0.5"}'

Postman Collection

ایجاد Collection

  1. Open Postman
  2. Create New → Collection
  3. نام: Exchange API

افزودن درخواست‌ها

Login

Method: POST
URL: {{BASE_URL}}/auth/login
Body: {"client_id": "{{CLIENT_ID}}", "client_secret": "{{CLIENT_SECRET}}"}
Tests: pm.environment.set("JWT_TOKEN", pm.response.json().access_token);

Get Symbols

Method: GET
URL: {{BASE_URL}}/api/exchange/v1/symbols
Headers: Authorization: Bearer {{JWT_TOKEN}}

Create Order

Method: POST
URL: {{BASE_URL}}/api/exchange/v1/orders
Headers: 
  - Authorization: Bearer {{JWT_TOKEN}}
  - Content-Type: application/json
Body: {
  "symbol": "BTC-IRR",
  "side": "buy",
  "type": "limit",
  "price": "1000000000",
  "quantity": "0.5"
}

Environment Variables

{
  "BASE_URL": "https://api.example.com",
  "CLIENT_ID": "your_client_id",
  "CLIENT_SECRET": "your_client_secret",
  "JWT_TOKEN": ""
}

ابزارهای تولید کد

Python

import requests

class ExchangeAPI:
    def __init__(self, base_url, client_id, client_secret):
        self.base_url = base_url
        self.token = self.login(client_id, client_secret)

    def login(self, client_id, client_secret):
        response = requests.post(
            f"{self.base_url}/auth/login",
            json={"client_id": client_id, "client_secret": client_secret}
        )
        return response.json()["access_token"]

    def get_symbols(self):
        response = requests.get(
            f"{self.base_url}/api/exchange/v1/symbols",
            headers={"Authorization": f"Bearer {self.token}"}
        )
        return response.json()

    def create_order(self, symbol, side, order_type, price, quantity):
        response = requests.post(
            f"{self.base_url}/api/exchange/v1/orders",
            headers={
                "Authorization": f"Bearer {self.token}",
                "Content-Type": "application/json"
            },
            json={
                "symbol": symbol,
                "side": side,
                "type": order_type,
                "price": price,
                "quantity": quantity
            }
        )
        return response.json()

# استفاده
api = ExchangeAPI("https://api.example.com", "client_id", "secret")
symbols = api.get_symbols()
order = api.create_order("BTC-IRR", "buy", "limit", "1000000000", "0.5")

Node.js

const axios = require('axios');

class ExchangeAPI {
  constructor(baseUrl, clientId, clientSecret) {
    this.baseUrl = baseUrl;
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.token = null;
  }

  async login() {
    const response = await axios.post(`${this.baseUrl}/auth/login`, {
      client_id: this.clientId,
      client_secret: this.clientSecret
    });
    this.token = response.data.access_token;
    return this.token;
  }

  async getSymbols() {
    const response = await axios.get(`${this.baseUrl}/api/exchange/v1/symbols`, {
      headers: { Authorization: `Bearer ${this.token}` }
    });
    return response.data;
  }

  async createOrder(symbol, side, type, price, quantity) {
    const response = await axios.post(
      `${this.baseUrl}/api/exchange/v1/orders`,
      { symbol, side, type, price, quantity },
      { headers: { Authorization: `Bearer ${this.token}` } }
    );
    return response.data;
  }
}

// استفاده
const api = new ExchangeAPI('https://api.example.com', 'client_id', 'secret');
await api.login();
const symbols = await api.getSymbols();
const order = await api.createOrder('BTC-IRR', 'buy', 'limit', '1000000000', '0.5');

نکات تکمیلی

تست خودکار

# اسکریپت تست
#!/bin/bash

# Login
export JWT_TOKEN=$(curl -s -X POST "$BASE_URL/auth/login" \
  -d '{"client_id":"...","client_secret":"..."}' | jq -r '.access_token')

# Test cases
echo "Testing API..."

# Test 1: Health
curl -s "$BASE_URL/api/exchange/v1/health" | jq -r '.status' | grep -q "up" && echo "✓ Health OK" || echo "✗ Health FAIL"

# Test 2: Symbols
curl -s "$BASE_URL/api/exchange/v1/symbols" -H "Authorization: Bearer $JWT_TOKEN" | jq -e '.items[0]' > /dev/null && echo "✓ Symbols OK" || echo "✗ Symbols FAIL"

# Test 3: Ticker
curl -s "$BASE_URL/api/exchange/v1/tickers/BTC-IRR" | jq -e '.symbol' > /dev/null && echo "✓ Ticker OK" || echo "✗ Ticker FAIL"

echo "Tests completed"

مستندات تعاملی

می‌توانید از این ابزارها استفاده کنید: - Swagger UI: نمایش زیبا و تعاملی - Redoc: نمایش مدرن و تمیز - RapiDoc: نمایش سریع و سبک


بعدی: مطالعه FAQ