Overview
The Short-URL API is configured entirely through environment variables. This approach ensures secure credential management and flexible deployment across different environments.All environment variables should be defined in a
.env file for local development or configured in your hosting platform’s environment settings for production.Required Environment Variables
These variables must be set for the API to function correctly.MongoDB connection string for database accessSource:
main.py:16Format:- Local:
mongodb://localhost:27017 - Atlas:
mongodb+srv://username:[email protected]/?retryWrites=true&w=majority - Replica Set:
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet
Secret key for JWT token signing and verificationSource: Example:
auth_utils.py:6Requirements:- Minimum 32 characters recommended
- Use cryptographically secure random string
- Keep secret and rotate periodically
Base URL for generated short linksSource: Response format:
main.py:18Usage: Used in the /create endpoint response to construct the full short URLFormat: https://your-domain.com (no trailing slash)Example:Optional Environment Variables
These variables have default values but can be customized for your deployment.Comma-separated list of allowed CORS originsSource: Production:
main.py:37Default: * (allow all origins)Format: Comma-separated URLs without spacesDevelopment:JWT token expiration time in minutesSource: Security considerations:
auth_utils.py:8Default: 5 minutesType: Integer (minutes)Example:- Shorter expiration = more secure but requires frequent re-authentication
- Longer expiration = better UX but higher security risk if token is compromised
- Use
/refresh_tokenendpoint to obtain new tokens without re-entering password
Comma-separated list of blacklisted URL patterns to prevent malicious short linksSource: Behavior: If any blacklist pattern is found in the submitted URL, creation fails with:Implementation: See
main.py:17Default: Empty (no blacklist)Format: Comma-separated domain fragmentsExample:main.py:78 and helper.py:23-27The blacklist uses substring matching. Adding “badsite.com” will block “https://badsite.com” and “https://subdomain.badsite.com”.
Environment Variables by Component
Authentication (auth_utils.py)
| Variable | Type | Default | Required | Description |
|---|---|---|---|---|
SECRET_KEY | string | - | Yes | JWT signing secret |
TOKEN_EXPIRE | integer | 5 | No | Token expiration (minutes) |
HS256 (see auth_utils.py:7)
Password Hashing: Uses pbkdf2_sha256 scheme (see auth_utils.py:10)
Application (main.py)
| Variable | Type | Default | Required | Description |
|---|---|---|---|---|
MONGO_URI | string | - | Yes | MongoDB connection string |
SURL_BASE | string | - | Yes | Base URL for short links |
ALLOWED_ORIGINS | string | * | No | CORS allowed origins |
URL_BLACKLIST | string | “ | No | Blacklisted URL patterns |
Example .env Files
Development Environment
.env.development
Production Environment
.env.production
Testing Environment
.env.test
Loading Environment Variables
Local Development
Usepython-dotenv to load variables from .env file:
startup.py
Docker
Pass environment variables indocker-compose.yml:
docker-compose.yml
Cloud Platforms
AWS Elastic Beanstalk
AWS Elastic Beanstalk
Set environment variables in the EB console or using
.ebextensions:Heroku
Heroku
Use Heroku CLI or dashboard:
Google Cloud Run
Google Cloud Run
Configure in
gcloud command or Cloud Console:Azure App Service
Azure App Service
Set in Application Settings:
Kubernetes
Kubernetes
Use ConfigMap and Secrets:
Security Best Practices
1. Never Commit Secrets
Add.env to .gitignore:
.gitignore
2. Use Different Keys Per Environment
- Development: Short, easy-to-remember keys
- Staging: Production-like secure keys
- Production: Cryptographically secure random keys
3. Rotate Secrets Regularly
- Rotate
SECRET_KEYevery 90 days - Update
MONGO_URIcredentials quarterly - Monitor for unauthorized access
4. Validate Environment Variables
Add startup validation:5. Use Secret Management Services
For production, use:- AWS Secrets Manager: Automatic rotation, audit logs
- Azure Key Vault: Integration with Azure services
- Google Secret Manager: Cloud-native secret storage
- HashiCorp Vault: Self-hosted, enterprise-grade
Troubleshooting
Variable Not Loading
None, check:
.envfile exists in correct directory- Variable name spelling (case-sensitive)
python-dotenvis installed and loaded- No spaces around
=in.envfile
MongoDB Connection Fails
- Verify
MONGO_URIformat - Check network connectivity
- Verify credentials
- Check IP whitelist (MongoDB Atlas)
- Test connection:
python -c "from pymongo import MongoClient; MongoClient(os.getenv('MONGO_URI')).admin.command('ping')"
CORS Errors
- Ensure
ALLOWED_ORIGINSincludes the requesting domain - Use exact protocol (
https://vshttp://) - No trailing slashes in origin URLs
- Check browser console for specific CORS error
Invalid Tokens
- Verify
SECRET_KEYhasn’t changed - Check
TOKEN_EXPIREsetting - Ensure server time is synchronized (JWT uses timestamps)
- Use
/refresh_tokento get new token