API Authentication
API Kalit Talab Qilinadi
Barcha API so'rovlar uchun Bearer token
autentifikatsiyasi zarur.
Rate Limits
- Standart: 1000 so'rov/soat
- Premium: 5000 so'rov/soat
- Enterprise: Unlimited
Authentication Headers
Authorization: Bearer {your-api-token}
Content-Type: application/json
Accept: application/json
X-API-Version: v1
Token Olish
POST /api/auth/login
{
"email": "admin@company.com",
"password": "your-secure-password"
}
Response:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
"user": {
"id": 1,
"name": "Admin User",
"role": "admin"
}
}
Token Yangilash
POST /api/auth/refresh
{
"refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
}
Response:
{
"access_token": "new-access-token...",
"expires_in": 3600
}
API Endpoints
Foydalanuvchilar va Rollar
GET
/api/v1/users
Foydalanuvchilar ro'yxati
POST
/api/v1/users
Yangi foydalanuvchi yaratish
GET
/api/v1/users/{id}
Foydalanuvchi ma'lumotlari
PUT
/api/v1/users/{id}
Foydalanuvchi ma'lumotlarini yangilash
Moliyaviy Operatsiyalar
GET
/api/v1/financial/transactions
Moliyaviy tranzaksiyalar
POST
/api/v1/financial/transactions
Yangi tranzaksiya yaratish
GET
/api/v1/financial/balance
Hisoblar balansi
GET
/api/v1/financial/reports
Moliyaviy hisobotlar
Ombor va Mahsulotlar
GET
/api/v1/inventory/products
Mahsulotlar ro'yxati
POST
/api/v1/inventory/movements
Mahsulot harakati (kirim/chiqim)
GET
/api/v1/inventory/stock
Qoldiqlar hisoboti
Savdo va Buyurtmalar
GET
/api/v1/sales/orders
Buyurtmalar ro'yxati
POST
/api/v1/sales/orders
Yangi buyurtma yaratish
GET
/api/v1/sales/analytics
Savdo analitikasi
CRM va Mijozlar
GET
/api/v1/crm/customers
Mijozlar ma'lumotlari
POST
/api/v1/crm/leads
Yangi lead yaratish
GET
/api/v1/crm/communications
Mijozlar bilan aloqa tarixi
HR va Hodimlar
GET
/api/v1/hr/employees
Hodimlar ro'yxati
GET
/api/v1/hr/attendance
Davomat ma'lumotlari
POST
/api/v1/hr/payroll
Ish haqi hisoblash
Hisobotlar
POST
/api/v1/reports/generate
Hisobot generatsiyasi
GET
/api/v1/reports/templates
Hisobot shablonlari
GET
/api/v1/reports/download/{id}
Hisobotni yuklab olish
Code Examples
JavaScript/Node.js
const axios = require('axios');
// API client yaratish
const api = axios.create({
baseURL: 'https://api.temurtech.loc/api/v1',
headers: {
'Authorization': 'Bearer your-token-here',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
// Foydalanuvchilar ro'yxatini olish
async function getUsers(page = 1, perPage = 15) {
try {
const response = await api.get('/users', {
params: { page, per_page: perPage }
});
return response.data;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// Yangi buyurtma yaratish
async function createOrder(orderData) {
try {
const response = await api.post('/sales/orders', {
customer_id: orderData.customerId,
items: orderData.items,
total_amount: orderData.totalAmount,
status: 'pending'
});
return response.data;
} catch (error) {
console.error('Order creation failed:', error.response?.data);
throw error;
}
}
// Moliyaviy hisobot olish
async function getFinancialReport(startDate, endDate) {
try {
const response = await api.post('/reports/generate', {
type: 'financial',
start_date: startDate,
end_date: endDate,
format: 'json'
});
return response.data;
} catch (error) {
console.error('Report generation failed:', error.response?.data);
throw error;
}
}
PHP/Laravel
<?php
use Illuminate\Support\Facades\Http;
class TemurtechApiClient
{
private $baseUrl;
private $token;
public function __construct($token)
{
$this->baseUrl = 'https://api.temurtech.loc/api/v1';
$this->token = $token;
}
private function headers()
{
return [
'Authorization' => 'Bearer ' . $this->token,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
];
}
// Mijozlar ro'yxatini olish
public function getCustomers($page = 1, $perPage = 15)
{
$response = Http::withHeaders($this->headers())
->get($this->baseUrl . '/crm/customers', [
'page' => $page,
'per_page' => $perPage
]);
if ($response->successful()) {
return $response->json();
}
throw new Exception('API request failed: ' . $response->body());
}
// Mahsulot qo'shish
public function addProduct($productData)
{
$response = Http::withHeaders($this->headers())
->post($this->baseUrl . '/inventory/products', [
'name' => $productData['name'],
'sku' => $productData['sku'],
'price' => $productData['price'],
'quantity' => $productData['quantity'],
'category_id' => $productData['category_id']
]);
if ($response->successful()) {
return $response->json();
}
throw new Exception('Product creation failed: ' . $response->body());
}
// Tranzaksiya yaratish
public function createTransaction($transactionData)
{
$response = Http::withHeaders($this->headers())
->post($this->baseUrl . '/financial/transactions', [
'type' => $transactionData['type'], // 'debit' or 'credit'
'amount' => $transactionData['amount'],
'account_id' => $transactionData['account_id'],
'description' => $transactionData['description'],
'reference' => $transactionData['reference'] ?? null
]);
if ($response->successful()) {
return $response->json();
}
throw new Exception('Transaction failed: ' . $response->body());
}
}
// Foydalanish misoli
$api = new TemurtechApiClient('your-api-token');
try {
$customers = $api->getCustomers(1, 20);
echo "Customers retrieved: " . count($customers['data']);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Python
import requests
import json
from datetime import datetime
class TemurtechAPI:
def __init__(self, token):
self.base_url = 'https://api.temurtech.loc/api/v1'
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
def get_employees(self, department=None, page=1, per_page=15):
"""Hodimlar ro'yxatini olish"""
params = {'page': page, 'per_page': per_page}
if department:
params['department'] = department
response = requests.get(
f'{self.base_url}/hr/employees',
headers=self.headers,
params=params
)
if response.status_code == 200:
return response.json()
else:
raise Exception(f'API Error: {response.status_code} - {response.text}')
def record_attendance(self, employee_id, check_in_time, check_out_time=None):
"""Davomat belgilash"""
data = {
'employee_id': employee_id,
'check_in': check_in_time.isoformat(),
'status': 'present'
}
if check_out_time:
data['check_out'] = check_out_time.isoformat()
response = requests.post(
f'{self.base_url}/hr/attendance',
headers=self.headers,
json=data
)
if response.status_code in [200, 201]:
return response.json()
else:
raise Exception(f'Attendance recording failed: {response.text}')
def get_inventory_report(self, warehouse_id=None):
"""Ombor hisoboti"""
params = {}
if warehouse_id:
params['warehouse_id'] = warehouse_id
response = requests.get(
f'{self.base_url}/inventory/stock',
headers=self.headers,
params=params
)
if response.status_code == 200:
return response.json()
else:
raise Exception(f'Inventory report failed: {response.text}')
def generate_sales_report(self, start_date, end_date, agent_id=None):
"""Savdo hisoboti generatsiya qilish"""
data = {
'type': 'sales_summary',
'start_date': start_date.strftime('%Y-%m-%d'),
'end_date': end_date.strftime('%Y-%m-%d'),
'format': 'json'
}
if agent_id:
data['agent_id'] = agent_id
response = requests.post(
f'{self.base_url}/reports/generate',
headers=self.headers,
json=data
)
if response.status_code in [200, 201]:
return response.json()
else:
raise Exception(f'Report generation failed: {response.text}')
# Foydalanish misoli
api = TemurtechAPI('your-api-token-here')
try:
# Hodimlar ro'yxati
employees = api.get_employees(department='sales', page=1)
print(f"Found {len(employees['data'])} employees")
# Bugungi savdo hisoboti
from datetime import date
today = date.today()
sales_report = api.generate_sales_report(today, today)
print(f"Sales report generated: {sales_report['report_id']}")
except Exception as e:
print(f"Error: {e}")
C#/.NET
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class TemurtechApiClient
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl = "https://api.temurtech.loc/api/v1";
public TemurtechApiClient(string token)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
_httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
}
// Moliyaviy balansni olish
public async Task GetFinancialBalanceAsync()
{
var response = await _httpClient.GetAsync($"{_baseUrl}/financial/balance");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(content);
}
throw new HttpRequestException($"API call failed: {response.StatusCode}");
}
// Yangi mijoz qo'shish
public async Task CreateCustomerAsync(object customerData)
{
var json = JsonConvert.SerializeObject(customerData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{_baseUrl}/crm/customers", content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(responseContent);
}
throw new HttpRequestException($"Customer creation failed: {response.StatusCode}");
}
// Hisobot yuklab olish
public async Task DownloadReportAsync(int reportId)
{
var response = await _httpClient.GetAsync($"{_baseUrl}/reports/download/{reportId}");
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsByteArrayAsync();
}
throw new HttpRequestException($"Report download failed: {response.StatusCode}");
}
}
// Foydalanish
var api = new TemurtechApiClient("your-api-token");
try
{
var balance = await api.GetFinancialBalanceAsync();
Console.WriteLine($"Current balance: {balance.total_balance}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Webhooks
Real-time Bildirishnomalar
Webhooks orqali muhim hodisalar haqida real-time xabar
olishingiz mumkin.
Webhook Events
POST
order.created
Yangi buyurtma yaratilganda
POST
payment.completed
To'lov amalga oshirilganda
POST
inventory.low_stock
Mahsulot kamayib ketganda
POST
user.created
Yangi foydalanuvchi ro'yxatdan o'tganda
POST
report.generated
Hisobot tayyor bo'lganda
Webhook Sozlash
POST /api/v1/webhooks
{
"url": "https://your-domain.com/webhook-endpoint",
"events": ["order.created", "payment.completed"],
"secret": "your-webhook-secret",
"active": true
}
Webhook Payload Misoli
{
"event": "order.created",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"order_id": 12345,
"customer_id": 678,
"total_amount": 150.50,
"status": "pending",
"items": [
{
"product_id": 101,
"quantity": 2,
"price": 75.25
}
]
},
"signature": "sha256=f7d7c9e8a2b3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9"
}
Webhook Verification (PHP)
Invalid signature
Error Handling
HTTP Status Codes
200
OK
So'rov muvaffaqiyatli bajarildi
201
Created
Yangi resurs yaratildi
400
Bad Request
Noto'g'ri so'rov parametrlari
401
Unauthorized
Autentifikatsiya talab qilinadi
403
Forbidden
Ruxsat berilmagan
404
Not Found
Resurs topilmadi
422
Validation Error
Ma'lumotlar validatsiyasidan o'tmadi
429
Rate Limit
So'rovlar soni limitdan oshib ketdi
500
Server Error
Ichki server xatosi
Error Response Format
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The given data was invalid",
"details": {
"email": ["Email format noto'g'ri"],
"amount": ["Miqdor musbat son bo'lishi kerak"]
},
"timestamp": "2024-01-15T10:30:00Z",
"request_id": "req_12345abcde"
}
}
Common Error Codes
INVALID_TOKEN - Noto'g'ri yoki muddati o'tgan token
INSUFFICIENT_PERMISSION - Ruxsat etilmagan amal
VALIDATION_ERROR - Ma'lumotlar validatsiya xatosi
RESOURCE_NOT_FOUND - Resurs topilmadi
DUPLICATE_RESOURCE - Resurs allaqachon mavjud
RATE_LIMIT_EXCEEDED - So'rovlar soni limitdan oshdi
INTERNAL_SERVER_ERROR - Ichki server xatosi
MAINTENANCE_MODE - Texnik ishlar rejimi
INVALID_API_VERSION - Noto'g'ri API versiyasi
Error Handling Best Practices
// JavaScript misoli
async function apiCall() {
try {
const response = await api.get('/users');
return response.data;
} catch (error) {
if (error.response) {
// Server javob berdi, lekin xato status bilan
switch (error.response.status) {
case 401:
// Token yangilash yoki qayta login
await refreshToken();
break;
case 429:
// Rate limit - biroz kutish
await delay(5000);
return apiCall(); // Qayta urinish
case 500:
// Server xatosi - log yozish
console.error('Server error:', error.response.data);
break;
default:
console.error('API error:', error.response.data);
}
} else {
// Network yoki boshqa xato
console.error('Network error:', error.message);
}
throw error;
}
}