Build and debug containerized Flask REST APIs with MySQL persistence, OpenWeatherMap integration, and Docker workflows
Expert guidance for building containerized Flask REST APIs with MySQL persistence, external API integration, and production-ready error handling patterns.
When working on this type of application, understand:
**Service Architecture:**
**Database Schema Pattern:**
**External API Integration:**
**Verify critical dependencies:**
**Start the environment:**
```bash
docker-compose up -d --build
```
**Watch logs for initialization:**
```bash
docker-compose logs -f web
```
**Expected output:** "Database initialized successfully!" after MySQL connection retry completes.
**When adding new endpoints:**
```python
@app.route('/your-endpoint', methods=['GET'])
def your_handler():
try:
connection = pymysql.connect(**DB_CONFIG, database='projeto')
with connection.cursor() as cursor:
cursor.execute("YOUR SQL")
result = cursor.fetchall()
return jsonify(result), 200
except pymysql.MySQLError as e:
return jsonify({'erro': str(e)}), 500
finally:
connection.close()
```
**Error handling strategy:**
**Access MySQL shell for schema inspection:**
```bash
docker exec -it mysql_clima mysql -u usuario -psenha projeto
```
**Common queries:**
```sql
SHOW TABLES;
DESCRIBE consultas_clima;
SELECT * FROM consultas_clima ORDER BY data_consulta DESC LIMIT 10;
```
**Reset database (clean slate):**
```bash
docker-compose down -v # Removes volumes
docker-compose up -d --build
```
**Quick smoke test:**
```bash
./demo.sh # Hits all major endpoints
```
**Full test suite:**
```bash
python test-api.py
```
**Manual API testing:**
```bash
curl http://localhost:5000/health
curl http://localhost:5000/clima/Sao%20Paulo
curl http://localhost:5000/historico?limit=10
curl http://localhost:5000/historico/Sao%20Paulo?limit=5
```
**Add OpenWeatherMap API key:**
Edit `docker-compose.yml`:
```yaml
services:
web:
environment:
WEATHER_API_KEY: your_actual_api_key_here # Get from openweathermap.org/api
```
**Restart after config changes:**
```bash
docker-compose up -d --build
```
**Requirements for live code updates:**
**Modify code → Save → Flask auto-reloads (no container restart needed)**
**"cryptography package required" error:**
```bash
cryptography==41.0.7
docker-compose up -d --build
```
**App can't connect to MySQL:**
```bash
docker-compose logs db
services:
web:
depends_on:
- db
```
**API returns 401 on /clima/<cidade>:**
**Interactive debugging:**
```bash
docker exec -it api_clima bash
env | grep WEATHER_API_KEY
curl http://localhost:5000/health
```
**Database initialization with retry:**
```python
def init_db():
for attempt in range(30):
try:
connection = pymysql.connect(**DB_CONFIG)
# Create database + tables
connection.close()
return
except pymysql.MySQLError:
time.sleep(2)
raise Exception("Failed to connect after 30 attempts")
```
**External API calls with timeout:**
```python
response = requests.get(
f"https://api.openweathermap.org/data/2.5/weather",
params={'q': cidade, 'appid': API_KEY, 'units': 'metric', 'lang': 'pt_br'},
timeout=10
)
```
**Query history with optional filtering:**
```python
limit = request.args.get('limit', default=10, type=int)
cursor.execute(
"SELECT * FROM consultas_clima WHERE cidade = %s ORDER BY data_consulta DESC LIMIT %s",
(cidade, limit)
)
```
**Start development:**
```bash
docker-compose up -d --build
docker-compose logs -f web
```
**Stop everything:**
```bash
docker-compose down
```
**Clean restart (wipes database):**
```bash
docker-compose down -v
docker-compose up -d --build
```
**View real-time logs:**
```bash
docker-compose logs -f web # Application
docker-compose logs -f db # MySQL
```
When suggesting code changes, always:
1. Preserve the retry initialization pattern
2. Use parameterized queries (prevent SQL injection)
3. Include proper error handling with status codes
4. Close database connections in finally blocks
5. Respect the 10-second timeout on external API calls
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-flask-weather-api-development/raw