Skip to content

Datahenge/contact_us_api

Repository files navigation

Contact Us API

A secure FastAPI backend for receiving contact form submissions from a public website. This API implements multiple layers of security including token-based authentication, request signing, rate limiting, and CORS protection.

Features

  • Token-based Authentication: Short-lived JWT tokens (5 minutes default)
  • Request Signing: HMAC-SHA256 signatures prevent replay attacks
  • Rate Limiting: Per-IP and per-origin rate limiting
  • CORS Protection: Configurable allowed origins
  • Structured Logging: JSON-formatted logs streamed to stdout (journald-compatible)
  • Email Notifications: Async SMTP email delivery
  • Security Headers: Standard security headers on all responses
  • Input Validation: Comprehensive Pydantic validation with sanitization

Installation

  1. Clone the repository:
cd contact_us_api
  1. Create a virtual environment:
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies:
pip install -e .

Or install without editable mode:

pip install .
  1. Configure the application:
    • Copy .env.example to .env and fill in your values
    • See Configuration Guide for all options
    • Important: Change default security secrets in production!

Configuration

The application uses environment variables for configuration. All variables use the CONTACT_API_ prefix to avoid conflicts with system variables.

For local development, create a .env file in the project root:

cp .env.example .env
# Edit .env with your configuration values

For a complete reference of all configuration options, see the Configuration Guide.

Running the Application

Development

cd src
python main.py

For production deployment instructions, including systemd service setup, see Production Deployment Guide.

Endpoints

The HTTP endpoints are covered in the Endpoints markdown document.

Frontend Integration

For detailed frontend integration examples and code snippets, see the Frontend Integration Guide.

Security Considerations

  1. Change Default Secrets: Always change the default token and signing secrets in production (see Configuration Guide)
  2. HTTPS Only: Use HTTPS in production to protect tokens and signatures in transit
  3. Secret Management: Use environment variables or a secrets manager (never commit secrets to version control)
  4. Signing Secret: The signing secret is kept secure on the server. Use the /api/signature endpoint to generate signatures server-side - never expose the signing secret to the frontend
  5. Rate Limiting: Adjust rate limits based on your traffic patterns
  6. CORS Origins: Only allow trusted origins in the CORS configuration
  7. Environment Variables: The .env file is excluded from git. Never commit secrets to the repository

For detailed security best practices, see the Configuration Guide and Production Deployment Guide.

Logging

Logs are streamed to stdout in JSON format (without timestamps, as journald provides them). When running as a systemd service, logs are captured by journald and can be viewed with journalctl.

Log entries include:

  • Request details (method, path, IP, origin)
  • Security events (token generation, validation failures)
  • Contact submissions
  • Rate limit violations
  • Errors and exceptions (with full tracebacks)

Error Codes

  • 400: Invalid request data or missing fields
  • 401: Invalid or expired token
  • 403: Invalid signature or CORS violation
  • 429: Rate limit exceeded (includes Retry-After header)
  • 500: Internal server error (generic message to client)

Testing

For information about testing the API and email configuration, see the Testing Guide.

Documentation

Additional documentation is available:

Development

Project Structure

contact_us_api/
├── LICENSE                  # MIT License
├── pyproject.toml           # Python project configuration and dependencies
├── README.md               # This file
├── tests/                  # Test scripts
│   ├── test_api.py         # Test script to simulate website interaction
│   └── test_email.py       # Test script to verify SMTP email credentials
├── docs/                   # Additional documentation
│   ├── configuration.md    # Configuration reference
│   ├── endpoints.md        # API endpoints documentation
│   ├── frontend.md         # Frontend integration guide
│   ├── production.md       # Production deployment guide
│   ├── testing.md          # Testing guide
│   └── Regarding_Pydantic.md  # Technical notes on Pydantic settings
├── docker/                 # Docker configuration
│   ├── README.md           # Docker setup and deployment guide
│   ├── Dockerfile          # Docker build configuration
│   └── docker-compose.yml  # Docker Compose example
└── src/
    ├── main.py             # FastAPI application entry point
    └── app/
        ├── __init__.py
        ├── models.py        # Pydantic models
        ├── security.py      # Token and signature handling
        ├── rate_limiter.py  # Rate limiting logic
        ├── email_service.py # SMTP email service
        ├── logger.py        # Logging configuration
        └── middleware.py    # CORS, security headers, etc.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Support

For issues or questions, contact your support email address.

About

Generic HTTP API to handle "Contact Us" forms on websites.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors