✨ Major reorganization: - Move all documentation to docs/ directory - Clean up root directory from temporary files - Add comprehensive project documentation - Implement Drone CI/CD pipeline 📁 Structure changes: - docs/SCRIPTS_README.md - Complete scripts guide - docs/DEPLOYMENT.md - Production deployment guide - docs/API.md - Comprehensive API documentation - patch/ - Temporary and test files - Clean .gitignore with proper exclusions 🚀 CI/CD Pipeline (.drone.yml): - Code quality checks (flake8, black, bandit) - Unit and integration testing - Docker image building and security scanning - Staging deployment automation - Production deployment on tags - Telegram notifications - Scheduled maintenance tasks 📖 Enhanced README.md: - Technology stack badges with icons - Drone CI build status badge - Comprehensive quick start guide - Clear project architecture - Links to all documentation 🔧 Additional improvements: - MIT License added - .gitkeep files for important directories - Improved .gitignore patterns - Professional project presentation 🎯 Result: Clean, professional project structure ready for production
12 KiB
🤖 SmartSolTech API Documentation
📡 API Endpoints Overview
SmartSolTech предоставляет RESTful API для взаимодействия с системой управления заказами и интеграции с внешними сервисами.
Base URL
Production: https://smartsoltech.kr/api/
Development: http://localhost:8000/api/
🔐 Аутентификация
API Token Authentication
Authorization: Token your-api-token-here
Получение токена:
# Через CLI
./cli manage drf_create_token <username>
# Через Django shell
./cli shell
>>> from django.contrib.auth.models import User
>>> from rest_framework.authtoken.models import Token
>>> user = User.objects.get(username='admin')
>>> token = Token.objects.create(user=user)
>>> print(token.key)
📋 Service Requests API
Создание заявки на услугу
POST /api/service-requests/
{
"client_name": "Иван Иванов",
"client_email": "ivan@example.com",
"client_phone": "+7 900 123-45-67",
"service_type": "web_development",
"description": "Разработка корпоративного сайта",
"budget_range": "50000-100000",
"preferred_contact": "email"
}
Response:
{
"id": 15,
"client_name": "Иван Иванов",
"client_email": "ivan@example.com",
"client_phone": "+7 900 123-45-67",
"service_type": "web_development",
"description": "Разработка корпоративного сайта",
"budget_range": "50000-100000",
"preferred_contact": "email",
"status": "pending",
"qr_code_url": "/static/qr_codes/request_15.png",
"chat_id": null,
"created_at": "2023-11-25T10:30:00Z",
"updated_at": "2023-11-25T10:30:00Z"
}
Получение списка заявок
GET /api/service-requests/
Query Parameters:
status- Фильтр по статусу (pending,confirmed,in_progress,completed,cancelled)service_type- Фильтр по типу услугиcreated_after- Заявки после определенной даты (ISO format)page- Номер страницыpage_size- Количество элементов на странице
curl -H "Authorization: Token your-token" \
"https://smartsoltech.kr/api/service-requests/?status=pending&page=1"
Получение конкретной заявки
GET /api/service-requests/{id}/
curl -H "Authorization: Token your-token" \
"https://smartsoltech.kr/api/service-requests/15/"
Обновление статуса заявки
PATCH /api/service-requests/{id}/
{
"status": "confirmed",
"chat_id": "123456789"
}
Проверка статуса заявки (публичный endpoint)
GET /api/check-request-status/{id}/
{
"status": "confirmed",
"message": "Ваша заявка подтверждена! Мы свяжемся с вами в ближайшее время."
}
🏢 Companies API
Получение информации о компании
GET /api/companies/
[
{
"id": 1,
"name": "SmartSolTech",
"description": "Инновационные IT решения для бизнеса",
"email": "info@smartsoltech.kr",
"phone": "+7 800 555-35-35",
"website": "https://smartsoltech.kr",
"address": "г. Москва, ул. Технологическая, д. 1",
"logo": "/media/company/logo.png",
"founded_year": 2023,
"employees_count": "10-50",
"specializations": [
"Веб-разработка",
"Мобильные приложения",
"DevOps"
]
}
]
👥 Team API
Получение команды
GET /api/team-members/
[
{
"id": 1,
"name": "Алексей Петров",
"position": "Lead Developer",
"bio": "10+ лет в веб-разработке",
"photo": "/media/team/alexey.jpg",
"linkedin": "https://linkedin.com/in/alexey",
"github": "https://github.com/alexey",
"email": "alexey@smartsoltech.kr",
"skills": ["Python", "Django", "React", "Docker"]
}
]
📊 Projects API
Получение портфолио
GET /api/projects/
[
{
"id": 1,
"title": "E-commerce платформа",
"description": "Современная платформа интернет-торговли",
"image": "/media/projects/ecommerce.jpg",
"url": "https://example-shop.com",
"category": "Веб-разработка",
"technologies": ["Django", "React", "PostgreSQL"],
"completion_date": "2023-10-15",
"client": "ООО Торговый Дом",
"status": "completed"
}
]
📝 Blog API
Получение статей блога
GET /api/blog/posts/
Query Parameters:
category- Фильтр по категорииtag- Фильтр по тегуpublished_after- Статьи после датыsearch- Поиск по заголовку и содержанию
[
{
"id": 1,
"title": "Тренды веб-разработки 2024",
"slug": "web-dev-trends-2024",
"excerpt": "Обзор основных трендов в веб-разработке",
"content": "Полный текст статьи...",
"author": {
"name": "Алексей Петров",
"photo": "/media/team/alexey.jpg"
},
"category": {
"name": "Разработка",
"slug": "development"
},
"tags": ["веб-разработка", "тренды", "2024"],
"featured_image": "/media/blog/trends-2024.jpg",
"published_at": "2023-11-20T10:00:00Z",
"reading_time": 8,
"views_count": 1234,
"is_featured": true
}
]
Получение конкретной статьи
GET /api/blog/posts/{slug}/
🏷️ Categories & Tags API
Категории услуг
GET /api/categories/
[
{
"id": 1,
"name": "Веб-разработка",
"slug": "web-development",
"description": "Создание современных веб-приложений",
"icon": "fas fa-code",
"services_count": 15
}
]
Теги
GET /api/tags/
[
{
"id": 1,
"name": "Django",
"slug": "django",
"color": "#092E20",
"posts_count": 12
}
]
📞 Contact API
Отправка сообщения
POST /api/contact/
{
"name": "Анна Смирнова",
"email": "anna@example.com",
"subject": "Вопрос по услугам",
"message": "Здравствуйте! Интересует разработка мобильного приложения.",
"phone": "+7 900 123-45-67"
}
Response:
{
"success": true,
"message": "Сообщение успешно отправлено. Мы ответим в ближайшее время.",
"id": 42
}
📊 Analytics API (Admin only)
Статистика заявок
GET /api/analytics/service-requests/
{
"total_requests": 156,
"pending_requests": 23,
"confirmed_requests": 89,
"completed_requests": 44,
"requests_by_month": [
{"month": "2023-10", "count": 45},
{"month": "2023-11", "count": 67}
],
"popular_services": [
{"service": "Веб-разработка", "count": 78},
{"service": "Мобильные приложения", "count": 34}
]
}
Статистика сайта
GET /api/analytics/site-stats/
{
"total_views": 12456,
"unique_visitors": 3456,
"popular_pages": [
{"path": "/services/", "views": 2345},
{"path": "/portfolio/", "views": 1876}
],
"referrers": [
{"source": "google.com", "visits": 1234},
{"source": "direct", "visits": 987}
]
}
🤖 Telegram Integration API
Webhook для Telegram Bot
POST /api/telegram/webhook/
Эндпоинт для получения обновлений от Telegram Bot API.
Отправка уведомления
POST /api/telegram/notify/
{
"chat_id": "123456789",
"message": "У вас новая заявка на услугу!",
"parse_mode": "HTML",
"disable_web_page_preview": true
}
🔧 Utilities API
Генерация QR-кода
POST /api/generate-qr/
{
"data": "https://smartsoltech.kr/confirm/15/",
"size": "200x200",
"format": "PNG"
}
Response:
{
"qr_code_url": "/static/qr_codes/custom_qr_1234567890.png",
"expires_at": "2023-11-26T10:30:00Z"
}
Загрузка файлов
POST /api/upload/
curl -X POST \
-H "Authorization: Token your-token" \
-F "file=@document.pdf" \
-F "category=documents" \
"https://smartsoltech.kr/api/upload/"
📱 Mobile App API
Конфигурация приложения
GET /api/mobile/config/
{
"app_name": "SmartSolTech",
"version": "1.0.0",
"api_version": "v1",
"features": {
"push_notifications": true,
"offline_mode": true,
"biometric_auth": true
},
"endpoints": {
"base_url": "https://smartsoltech.kr/api/",
"websocket_url": "wss://smartsoltech.kr/ws/"
}
}
🚨 Error Handling
Стандартные HTTP коды
200 OK- Успешный запрос201 Created- Ресурс создан400 Bad Request- Некорректные данные401 Unauthorized- Необходима аутентификация403 Forbidden- Недостаточно прав404 Not Found- Ресурс не найден429 Too Many Requests- Превышен лимит запросов500 Internal Server Error- Ошибка сервера
Формат ошибок
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Некорректные данные",
"details": {
"email": ["Введите корректный email адрес"],
"phone": ["Номер телефона обязателен"]
},
"timestamp": "2023-11-25T10:30:00Z",
"request_id": "req_1234567890"
}
}
🔒 Rate Limiting
Лимиты для разных типов пользователей
- Anonymous: 100 запросов в час
- Authenticated: 1000 запросов в час
- Premium: 10000 запросов в час
Headers ответа
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1635724800
📚 SDK и библиотеки
Python SDK
from smartsoltech_api import SmartSolTechClient
client = SmartSolTechClient(
api_key='your-api-key',
base_url='https://smartsoltech.kr/api/'
)
# Создание заявки
request = client.service_requests.create({
'client_name': 'Test Client',
'service_type': 'web_development',
'description': 'Test request'
})
# Получение статистики
stats = client.analytics.get_service_requests_stats()
JavaScript SDK
import { SmartSolTechAPI } from 'smartsoltech-js-sdk';
const api = new SmartSolTechAPI({
apiKey: 'your-api-key',
baseURL: 'https://smartsoltech.kr/api/'
});
// Создание заявки
const request = await api.serviceRequests.create({
clientName: 'Test Client',
serviceType: 'web_development',
description: 'Test request'
});
// Получение проектов
const projects = await api.projects.list();
🧪 Testing
Тестирование API
# Запуск тестов API
./cli manage test api.tests
# Тестирование конкретного эндпоинта
./cli manage test api.tests.test_service_requests
# Запуск coverage
./cli exec coverage run --source='.' manage.py test
./cli exec coverage report
Примеры запросов
# Получение токена
curl -X POST http://localhost:8000/api/auth/token/ \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}'
# Создание заявки
curl -X POST http://localhost:8000/api/service-requests/ \
-H "Authorization: Token your-token" \
-H "Content-Type: application/json" \
-d '{
"client_name": "Test Client",
"client_email": "test@example.com",
"service_type": "web_development",
"description": "Test request"
}'
🎯 Следующие шаги: Развертывание | Управление скриптами