mockapi/README.md.backup
2026-03-16 05:47:01 +00:00

257 lines
9.2 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Configurable Mock API with Admin Interface
A lightweight, configurable mock API application in Python that allows dynamic endpoint management via an admin interface. The API serves customizable responses stored in a SQLite database with template variable support.
## Features
- **Dynamic Endpoint Configuration**: Create, read, update, and delete API endpoints through a web-based admin interface.
- **Template Variable Support**: Response bodies can include Jinja2 template variables (e.g., `{{ user_id }}`, `{{ timestamp }}`) populated from path parameters, query strings, headers, request body, system variables, and endpoint defaults.
- **Dynamic Route Registration**: Endpoints are registered/unregistered at runtime without restarting the server.
- **Admin Interface**: Secure web UI with session-based authentication for managing endpoints.
- **Production Ready**: Uses Waitress WSGI server, SQLAlchemy async, and FastAPI with proper error handling and security measures.
## Technology Stack
- **Framework**: FastAPI (with automatic OpenAPI documentation)
- **Server**: Waitress (production WSGI server)
- **Database**: SQLite with SQLAlchemy 2.0 async ORM
- **Templating**: Jinja2 with sandboxed environment
- **Authentication**: Session-based with bcrypt password hashing
- **Frontend**: Bootstrap 5 (CDN) for admin UI
## Project Structure
```
mockapi/
├── app.py # FastAPI application factory & lifespan
├── config.py # Configuration (Pydantic Settings)
├── database.py # SQLAlchemy async database setup
├── dependencies.py # FastAPI dependencies
├── example_usage.py # Integration test & demonstration script
├── middleware/
│ └── auth_middleware.py # Admin authentication middleware
├── models/
│ └── endpoint_model.py # Endpoint SQLAlchemy model
├── observers/
│ └── __init__.py # Observer pattern placeholder
├── repositories/
│ └── endpoint_repository.py # Repository pattern for endpoints
├── run.py # Application entry point (production)
├── services/
│ ├── route_service.py # Dynamic route registration/management
│ └── template_service.py # Jinja2 template rendering
├── controllers/
│ └── admin_controller.py # Admin UI routes
├── schemas/
│ └── endpoint_schema.py # Pydantic schemas for validation
├── templates/ # Jinja2 HTML templates
│ ├── base.html # Base layout
│ └── admin/
│ ├── login.html # Login page
│ ├── dashboard.html # Admin dashboard
│ ├── endpoints.html # Endpoint list
│ └── endpoint_form.html # Create/edit endpoint
├── static/
│ └── css/ # Static CSS (optional)
├── tests/ # Test suite
│ ├── test_admin.py # Admin authentication tests
│ ├── test_endpoint_repository.py
│ └── test_route_manager_fix.py
├── utils/ # Utility modules
│ └── __init__.py
├── requirements.txt # Python dependencies
├── .env.example # Example environment variables
├── .env # Local environment variables (create from .env.example)
├── run_example.sh # Script to run the integration test
└── README.md # This file
```
## Installation
1. **Clone or extract the project**:
```bash
cd mockapi
```
2. **Create a virtual environment** (optional but recommended):
```bash
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. **Install dependencies**:
```bash
pip install -r requirements.txt
```
4. **Configure environment variables**:
```bash
cp .env.example .env
# Edit .env with your settings (admin password, secret key, etc.)
```
Example `.env`:
```ini
DATABASE_URL=sqlite+aiosqlite:///./mockapi.db
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123 # Change this in production!
SECRET_KEY=your-secret-key-here # Change this!
DEBUG=True # Set to False in production
```
5. **Initialize the database** (tables are created automatically on first run).
## Running the Application
### Development (with autoreload)
```bash
uvicorn app:app --reload --host 0.0.0.0 --port 8000
```
### Production (with Waitress)
```bash
waitress-serve --host=0.0.0.0 --port=8000 --threads=4 app:app
```
The server will start on `http://localhost:8000`.
## Usage
### 1. Access the Admin Interface
- Open `http://localhost:8000/admin/login`
- Log in with the credentials set in `.env` (default: `admin` / `admin123`)
### 2. Create a Mock Endpoint
1. Navigate to **Endpoints** → **Create New**.
2. Fill in the form:
- **Route**: `/api/greeting/{name}` (supports path parameters)
- **Method**: GET
- **Response Body**: `{ "message": "Hello, {{ name }}!" }`
- **Response Code**: 200
- **Content-Type**: `application/json`
- **Variables**: `{ "server": "mock-api" }` (optional defaults)
3. Click **Create**.
### 3. Call the Mock Endpoint
```bash
curl http://localhost:8000/api/greeting/World
```
Response:
```json
{ "message": "Hello, World!" }
```
### 4. Template Variables
The following variable sources are available in response templates:
| Source | Example variable | Usage in template |
|--------|------------------|-------------------|
| Path parameters | `{{ name }}` | `/users/{id}` → `{{ id }}` |
| Query parameters | `{{ query.page }}` | `?page=1` → `{{ page }}` |
| Request headers | `{{ header.authorization }}` | `Authorization: Bearer token` |
| Request body | `{{ body.user.email }}` | JSON request body |
| System variables | `{{ timestamp }}`, `{{ request_id }}` | Automatically injected |
| Endpoint defaults | `{{ server }}` | Defined in endpoint variables |
### 5. Admin Functions
- **List endpoints** with pagination and filtering
- **Edit** existing endpoints (changes take effect immediately)
- **Activate/deactivate** endpoints without deletion
- **Delete** endpoints (removes route)
- **Dashboard** with statistics (total endpoints, active routes, etc.)
## Security Considerations
- **Admin authentication**: Uses bcrypt password hashing. Store a strong password hash in production.
- **Session management**: Signed cookies with configurable secret key.
- **Template sandboxing**: Jinja2 environment restricted with `SandboxedEnvironment` and `StrictUndefined`.
- **Request size limits**: Maximum body size of 1MB to prevent DoS.
- **Route validation**: Prevents path traversal (`..`) and other unsafe patterns.
- **SQL injection protection**: All queries use SQLAlchemy ORM.
## Configuration Options
See `config.py` for all available settings. Key environment variables:
| Variable | Default | Description |
|----------|---------|-------------|
| `DATABASE_URL` | `sqlite+aiosqlite:///./mockapi.db` | SQLAlchemy database URL |
| `ADMIN_USERNAME` | `admin` | Admin login username |
| `ADMIN_PASSWORD` | `admin123` | Admin login password (plaintext) |
| `SECRET_KEY` | `yoursecretkeyherechangeme` | Session signing secret |
| `DEBUG` | `False` | Enable debug mode (more logging, relaxed validation) |
**Warning**: In production (`DEBUG=False`), the default `ADMIN_PASSWORD` and `SECRET_KEY` will cause validation errors. You must set unique values via environment variables.
## API Documentation
FastAPI automatically provides OpenAPI documentation at:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
The dynamic mock endpoints are not listed in the OpenAPI schema (they are registered at runtime).
## Development & Testing
### Running Tests
Run tests with pytest:
```bash
pytest tests/
```
The test suite includes:
- Unit tests for repository and service layers
- Integration tests for admin authentication
- Template rendering tests
### Example Integration Test
A readytorun integration test demonstrates the core functionality:
```bash
# Make the script executable (Linux/macOS)
chmod +x run_example.sh
# Run the example
./run_example.sh
```
Or directly with Python:
```bash
python example_usage.py
```
The example script will:
1. Start the FastAPI app (via TestClient)
2. Log in as admin
3. Create a mock endpoint with template variables
4. Call the endpoint and verify the response
5. Report success or failure
This is a great way to verify that the API is working correctly after installation.
## Limitations & Future Enhancements
- **Current limitations**:
- SQLite only (but can be extended to PostgreSQL via `DATABASE_URL`)
- Single admin user (no multiuser support)
- No request logging/history
- **Possible extensions**:
- Import/export endpoints as JSON/YAML
- Request logging and analytics
- WebSocket notifications for admin actions
- Multiple admin users with roles
- Rate limiting per endpoint
- CORS configuration
## License
This project is provided as-is for demonstration purposes. Use at your own risk.
## Acknowledgments
- Built with [FastAPI](https://fastapi.tiangolo.com/), [SQLAlchemy](https://www.sqlalchemy.org/), and [Jinja2](https://jinja.palletsprojects.com/).
- Admin UI uses [Bootstrap 5](https://getbootstrap.com/) via CDN.