Files
tm_back/docs/setup/SWAGGER_SETUP.md
T
n.nakhostin 9119e2383e Add configuration file and update server settings
- Introduced a new `config.yaml` file for managing server, database, cache, queue, AI, scraping, logging, and rate limiting configurations.
- Updated `docker-compose.yml` to reflect the new server port (8081) and adjusted health check endpoints accordingly.
- Modified `Dockerfile` to expose the new server port.
- Updated `README.md` to reflect changes in server configuration and added documentation for the new configuration structure.
- Added test scripts for server and Swagger documentation testing.
- Refactored customer domain structure to align with new configuration settings and improve maintainability.
2025-08-02 12:37:04 +03:30

313 lines
7.2 KiB
Markdown

# Swagger API Documentation Setup
This document explains how to use and maintain the Swagger API documentation for the Tender Management Backend.
## 📚 Overview
The API documentation is generated using [Swag](https://github.com/swaggo/swag) and served using [echo-swagger](https://github.com/swaggo/echo-swagger). The documentation provides an interactive interface to explore and test all API endpoints.
## 🚀 Quick Start
### 1. Generate Documentation
```bash
# Generate Swagger documentation
make docs
# Or manually
swag init -g cmd/web/main.go -o cmd/web/docs
```
### 2. Start Server with Documentation
```bash
# Build and run with documentation
make run-docs
# Or manually
make build
./bin/web
```
### 3. Access Documentation
Open your browser and navigate to:
- **Swagger UI**: http://localhost:8081/swagger/index.html
- **Health Check**: http://localhost:8081/health
## 📋 Available Endpoints
### 🔐 Authentication
- `POST /api/customers/login` - Customer login
- `POST /api/customers/refresh-token` - Refresh access token
### 👤 Customer Profile (Protected)
- `GET /api/customers/profile` - Get customer profile
- `PUT /api/customers/profile` - Update customer profile
- `PUT /api/customers/change-password` - Change password
### 📱 Device Management (Protected)
- `POST /api/customers/device-token` - Add device token
- `DELETE /api/customers/device-token` - Remove device token
### 👥 Admin Operations (Admin Protected)
- `POST /api/admin/customers/register` - Register new customer
- `GET /api/admin/customers` - List customers
- `GET /api/admin/customers/{id}` - Get customer by ID
- `PUT /api/admin/customers/{id}/status` - Update customer status
## 🛠️ Development
### Adding New Endpoints
1. **Add Swagger Annotations** to your handler functions:
```go
// @Summary Endpoint summary
// @Description Detailed description
// @Tags tag-name
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param param-name param-type param-required "param description"
// @Success 200 {object} response.APIResponse{data=YourResponseType} "Success description"
// @Failure 400 {object} response.APIResponse "Error description"
// @Router /api/endpoint [method]
func (h *Handler) YourHandler(c echo.Context) error {
// Your handler implementation
}
```
2. **Regenerate Documentation**:
```bash
make docs
```
### Swagger Annotation Examples
#### Basic GET Endpoint
```go
// @Summary Get resource
// @Description Get a resource by ID
// @Tags resources
// @Accept json
// @Produce json
// @Param id path string true "Resource ID"
// @Success 200 {object} response.APIResponse{data=ResourceResponse}
// @Failure 404 {object} response.APIResponse
// @Router /api/resources/{id} [get]
```
#### POST with Request Body
```go
// @Summary Create resource
// @Description Create a new resource
// @Tags resources
// @Accept json
// @Produce json
// @Param resource body CreateResourceForm true "Resource data"
// @Success 201 {object} response.APIResponse{data=ResourceResponse}
// @Failure 400 {object} response.APIResponse
// @Router /api/resources [post]
```
#### Protected Endpoint
```go
// @Summary Protected endpoint
// @Description This endpoint requires authentication
// @Tags resources
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.APIResponse
// @Failure 401 {object} response.APIResponse
// @Router /api/protected [get]
```
## 📁 File Structure
```
cmd/web/
├── main.go # Main application entry point
├── bootstrap.go # Server initialization
└── docs/ # Generated Swagger documentation
├── docs.go # Generated docs
├── swagger.json # OpenAPI specification
└── swagger.yaml # OpenAPI specification (YAML)
internal/customer/
├── handler.go # HTTP handlers with Swagger annotations
├── form.go # Request/response forms
└── ...
pkg/response/
└── response.go # Standard API response types
```
## 🔧 Configuration
### Swagger Configuration
The main Swagger configuration is in `cmd/web/docs.go`:
```go
// @title Tender Management API
// @version 1.0.0
// @description This is the API documentation for the Tender Management System.
// @host localhost:8081
// @BasePath /api/v1
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
```
### Server Configuration
The Swagger endpoint is registered in `cmd/web/bootstrap.go`:
```go
// Add Swagger documentation endpoint
e.GET("/swagger/*", echoSwagger.WrapHandler)
```
## 🧪 Testing
### Using the Test Script
```bash
# Run the test script
./test_swagger.sh
```
This script will:
1. Build the application
2. Start the server
3. Display all available endpoints
4. Provide access URLs
### Manual Testing
1. **Start the server**:
```bash
make run-docs
```
2. **Access Swagger UI**:
- Open http://localhost:8081/swagger/index.html
- Explore and test endpoints interactively
3. **Test Health Check**:
```bash
curl http://localhost:8081/health
```
## 📝 Response Types
### Standard Response Structure
All API responses follow this structure:
```json
{
"success": true,
"message": "Operation successful",
"data": {
// Response data
},
"meta": {
// Pagination metadata (if applicable)
},
"error": {
// Error details (if applicable)
}
}
```
### Error Response
```json
{
"success": false,
"message": "Error message",
"error": {
"code": "ERROR_CODE",
"message": "Detailed error message",
"details": "Additional details"
}
}
```
## 🔐 Authentication
### Bearer Token Authentication
Most endpoints require Bearer token authentication:
1. **Login** to get access token:
```bash
curl -X POST http://localhost:8081/api/customers/login \
-H "Content-Type: application/json" \
-d '{"email": "user@example.com", "password": "password"}'
```
2. **Use the token** in subsequent requests:
```bash
curl -X GET http://localhost:8081/api/customers/profile \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```
## 🚨 Troubleshooting
### Common Issues
1. **Documentation not updating**:
```bash
make clean
make docs
make build
```
2. **Swagger annotations not recognized**:
- Ensure annotations are directly above the function
- Check for syntax errors in annotations
- Verify import paths are correct
3. **Server won't start**:
- Check if port 8081 is available
- Verify MongoDB connection
- Check configuration files
### Debug Commands
```bash
# Check if swag is installed
swag --version
# Generate docs with verbose output
swag init -g cmd/web/main.go -o cmd/web/docs --parseDependency
# Check generated files
ls -la cmd/web/docs/
```
## 📚 Additional Resources
- [Swag Documentation](https://github.com/swaggo/swag)
- [Echo Swagger](https://github.com/swaggo/echo-swagger)
- [OpenAPI Specification](https://swagger.io/specification/)
- [Swagger UI](https://swagger.io/tools/swagger-ui/)
## 🤝 Contributing
When adding new endpoints:
1. Add comprehensive Swagger annotations
2. Include all possible response codes
3. Provide meaningful examples
4. Test the documentation in Swagger UI
5. Update this documentation if needed
## 📄 License
This documentation is part of the Tender Management Backend project.