FastApi-ISS/README.md
2025-08-07 00:16:18 +03:30

258 lines
6.8 KiB
Markdown

# FastAPI ISS Project
A FastAPI application with Docker and docker-compose support.
## Features
- FastAPI REST API with CRUD operations
- PostgreSQL database integration
- SQLAlchemy ORM with Alembic migrations
- Docker containerization
- Docker Compose for easy deployment
- Health check endpoints
- CORS middleware enabled
- Auto-generated API documentation
## API Endpoints
- `GET /` - Welcome message
- `GET /health` - Health check
- `GET /items` - Get all items
- `GET /items/{item_id}` - Get specific item
- `POST /items` - Create new item
- `PUT /items/{item_id}` - Update item
- `DELETE /items/{item_id}` - Delete item
## Quick Start with Docker Compose
1. **Set up environment variables:**
```bash
# Copy the example environment file
cp env.example .env
# Edit the .env file with your secure passwords
# nano .env # or use your preferred editor
```
2. **Build and start the application:**
```bash
docker-compose up --build
```
3. **Access the application:**
- API: http://localhost:8000
- Interactive API docs: http://localhost:8000/docs
- ReDoc documentation: http://localhost:8000/redoc
4. **Stop the application:**
```bash
docker-compose down
```
## Development
### Running locally without Docker
1. **Install dependencies:**
```bash
pip install -r requirements.txt
```
2. **Run the application:**
```bash
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
### Docker Commands
**Build the image:**
```bash
docker build -t fastapi-iss .
```
**Run the container:**
```bash
docker run -p 8000:8000 fastapi-iss
```
**Run in detached mode:**
```bash
docker run -d -p 8000:8000 --name fastapi-app fastapi-iss
```
## API Examples
### Create an item
```bash
curl -X POST "http://localhost:8000/items" \
-H "Content-Type: application/json" \
-d '{"name": "Sample Item", "description": "A sample item", "price": 29.99}'
```
### Get all items
```bash
curl "http://localhost:8000/items"
```
### Get specific item
```bash
curl "http://localhost:8000/items/1"
```
### Update item
```bash
curl -X PUT "http://localhost:8000/items/1" \
-H "Content-Type: application/json" \
-d '{"name": "Updated Item", "description": "Updated description", "price": 39.99}'
```
### Delete item
```bash
curl -X DELETE "http://localhost:8000/items/1"
```
### Database Connection
You can connect to the PostgreSQL database directly:
```bash
# Using psql (if installed)
psql -h localhost -p ${POSTGRES_PORT} -U ${POSTGRES_USER} -d ${POSTGRES_DB}
# Using Docker
docker exec -it fastapi-iss-postgres-1 psql -U ${POSTGRES_USER} -d ${POSTGRES_DB}
```
## Project Structure
```
FastApi-ISS/
├── main.py # FastAPI application
├── database.py # Database configuration and models
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── docker-compose.yml # Docker Compose configuration
├── env.example # Example environment variables
├── .env # Environment variables (create from env.example)
├── alembic.ini # Alembic configuration
├── alembic/ # Database migrations
│ ├── env.py # Alembic environment
│ └── script.py.mako # Migration template
├── .dockerignore # Docker ignore file
├── .gitignore # Git ignore file
└── README.md # This file
```
## Environment Variables
The application uses environment variables for configuration. Copy `env.example` to `.env` and customize the values:
### Database Configuration
- `POSTGRES_DB`: Database name (default: `fastapi_db`)
- `POSTGRES_USER`: Database user (default: `fastapi_user`)
- `POSTGRES_PASSWORD`: Database password (**CHANGE THIS**)
- `POSTGRES_HOST`: Database host (default: `postgres`)
- `POSTGRES_PORT`: Database port (default: `5432`)
- `DATABASE_URL`: Full database connection string (auto-generated from above)
### Application Configuration
- `PYTHONPATH`: Python path (default: `/app`)
- `PYTHONUNBUFFERED`: Python output buffering (default: `1`)
- `FASTAPI_TITLE`: Application title
- `FASTAPI_DESCRIPTION`: Application description
- `FASTAPI_VERSION`: Application version
### Security Configuration
- `SECRET_KEY`: Secret key for JWT tokens (**CHANGE THIS**)
- `ALGORITHM`: JWT algorithm (default: `HS256`)
- `ACCESS_TOKEN_EXPIRE_MINUTES`: Token expiration time
### CORS Configuration
- `ALLOWED_ORIGINS`: Allowed origins for CORS
- `ALLOWED_CREDENTIALS`: Allow credentials in CORS
- `ALLOWED_METHODS`: Allowed HTTP methods
- `ALLOWED_HEADERS`: Allowed HTTP headers
### Logging
- `LOG_LEVEL`: Logging level (default: `INFO`)
## Database
The application uses PostgreSQL with the following configuration (configurable via environment variables):
- **Database**: `fastapi_db` (configurable via `POSTGRES_DB`)
- **User**: `fastapi_user` (configurable via `POSTGRES_USER`)
- **Password**: Configurable via `POSTGRES_PASSWORD` (change this!)
- **Port**: `5432` (configurable via `POSTGRES_PORT`)
### Database Migrations
To run database migrations:
```bash
# Generate a new migration
alembic revision --autogenerate -m "Description of changes"
# Apply migrations
alembic upgrade head
# Rollback migrations
alembic downgrade -1
```
## Health Checks
The application includes health checks that can be accessed at:
- Docker health check: `http://localhost:8000/health`
- Docker Compose health check: Configured in docker-compose.yml
## Security
### Environment Variables
- **Never commit `.env` files** to version control
- Use `env.example` as a template for your `.env` file
- Change all default passwords and secret keys
- Use strong, unique passwords for production
### Production Deployment
- Change all default credentials
- Use strong secret keys
- Configure proper CORS settings
- Enable HTTPS
- Use environment-specific `.env` files
### Database Security
- Use strong database passwords
- Limit database access to necessary users only
- Regularly update dependencies
- Monitor database logs
## Troubleshooting
1. **Port already in use:**
- Change the port in docker-compose.yml or use a different port
- Kill existing processes using the port
2. **Docker build fails:**
- Ensure Docker is running
- Clear Docker cache: `docker system prune -a`
3. **Application not starting:**
- Check logs: `docker-compose logs`
- Verify all files are present in the project directory
4. **Database connection issues:**
- Verify `.env` file exists and has correct values
- Check if PostgreSQL container is running: `docker-compose ps`
- Check database logs: `docker-compose logs postgres`
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test with Docker Compose
5. Submit a pull request
## License
This project is open source and available under the MIT License.