Create Weather Data API with OpenWeatherMap integration

- Implemented FastAPI application structure
- Added OpenWeatherMap API integration
- Created SQLite database with SQLAlchemy
- Setup Alembic for database migrations
- Added health check endpoint
- Created comprehensive README

generated with BackendIM... (backend.im)
This commit is contained in:
Automated Action 2025-05-12 13:51:42 +00:00
parent 524d6fb716
commit 6705b7a5e2
21 changed files with 782 additions and 2 deletions

View File

@ -1,3 +1,68 @@
# FastAPI Application
# Weather Data API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A FastAPI application that retrieves weather data from OpenWeatherMap and stores it in a SQLite database.
## Features
- Fetch current weather data from OpenWeatherMap
- Store weather data in a SQLite database
- Track weather history for cities
- RESTful API with FastAPI
- Database migrations with Alembic
- Health check endpoint
## Setup
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run the application:
```bash
uvicorn main:app --reload
```
## API Endpoints
### Weather Endpoints
- `GET /api/v1/weather/current/{city_name}` - Get current weather for a city
- `POST /api/v1/weather/current` - Get current weather using request body
- `GET /api/v1/weather/cities` - List all cities
- `GET /api/v1/weather/cities/{city_id}` - Get city details
- `GET /api/v1/weather/history/{city_id}` - Get weather history for a city
### Health Check
- `GET /health` - Check application health
## Database
The application uses SQLite with SQLAlchemy. The database is stored in `/app/storage/db/db.sqlite`.
### Migrations
Database migrations are managed with Alembic:
```bash
# Apply migrations
alembic upgrade head
# Create a new migration
alembic revision -m "description"
```
## Environment Variables
- `OPENWEATHERMAP_API_KEY` - Your OpenWeatherMap API key (default: `bd5e378503939ddaee76f12ad7a97608`)
## Documentation
The API documentation is available at:
- Swagger UI: `/docs`
- ReDoc: `/redoc`

102
alembic.ini Normal file
View File

@ -0,0 +1,102 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

77
alembic/env.py Normal file
View File

@ -0,0 +1,77 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.db.base import Base
from app.models.weather import City, WeatherData
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
alembic/script.py.mako Normal file
View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,58 @@
"""initial migration
Revision ID: 55e2b32824ab
Revises:
Create Date: 2023-10-10 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '55e2b32824ab'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create cities table
op.create_table('cities',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('country', sa.String(), nullable=True),
sa.Column('latitude', sa.Float(), nullable=True),
sa.Column('longitude', sa.Float(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_cities_id'), 'cities', ['id'], unique=False)
op.create_index(op.f('ix_cities_name'), 'cities', ['name'], unique=False)
# Create weather_data table
op.create_table('weather_data',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('city_id', sa.Integer(), nullable=True),
sa.Column('temperature', sa.Float(), nullable=True),
sa.Column('feels_like', sa.Float(), nullable=True),
sa.Column('humidity', sa.Integer(), nullable=True),
sa.Column('pressure', sa.Integer(), nullable=True),
sa.Column('wind_speed', sa.Float(), nullable=True),
sa.Column('wind_direction', sa.Integer(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('weather_main', sa.String(), nullable=True),
sa.Column('weather_icon', sa.String(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['city_id'], ['cities.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_weather_data_id'), 'weather_data', ['id'], unique=False)
def downgrade():
op.drop_index(op.f('ix_weather_data_id'), table_name='weather_data')
op.drop_table('weather_data')
op.drop_index(op.f('ix_cities_name'), table_name='cities')
op.drop_index(op.f('ix_cities_id'), table_name='cities')
op.drop_table('cities')

0
app/api/__init__.py Normal file
View File

25
app/api/health.py Normal file
View File

@ -0,0 +1,25 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from datetime import datetime
from app.db.session import get_db
router = APIRouter()
@router.get("/health", tags=["health"])
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint
"""
try:
# Check database connection
db.execute("SELECT 1")
db_status = "healthy"
except Exception as e:
db_status = f"unhealthy: {str(e)}"
return {
"status": "healthy",
"timestamp": datetime.utcnow(),
"database": db_status
}

0
app/api/v1/__init__.py Normal file
View File

7
app/api/v1/api.py Normal file
View File

@ -0,0 +1,7 @@
from fastapi import APIRouter
from app.api.v1.endpoints import weather
api_router = APIRouter()
api_router.include_router(weather.router, prefix="/weather", tags=["weather"])

View File

View File

@ -0,0 +1,85 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.schemas.weather import WeatherResponse, City, CityWeather, CityQuery
from app.services.weather import (
get_and_save_weather,
get_cities,
get_city_by_id,
get_weather_history_by_city
)
router = APIRouter()
@router.get("/current/{city_name}", response_model=WeatherResponse)
async def get_current_weather(
city_name: str,
country_code: str = None,
db: Session = Depends(get_db)
):
"""
Get current weather for a specific city
"""
try:
result = await get_and_save_weather(db, city_name, country_code)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/current", response_model=WeatherResponse)
async def get_current_weather_by_query(
query: CityQuery,
db: Session = Depends(get_db)
):
"""
Get current weather for a city using request body
"""
try:
result = await get_and_save_weather(db, query.city, query.country)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/cities", response_model=List[City])
def list_cities(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
"""
List all cities
"""
return get_cities(db, skip=skip, limit=limit)
@router.get("/cities/{city_id}", response_model=City)
def get_city(
city_id: int,
db: Session = Depends(get_db)
):
"""
Get city by ID
"""
city = get_city_by_id(db, city_id)
if not city:
raise HTTPException(status_code=404, detail=f"City with ID {city_id} not found")
return city
@router.get("/history/{city_id}", response_model=CityWeather)
def get_weather_history(
city_id: int,
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
"""
Get weather history for a specific city
"""
city = get_city_by_id(db, city_id)
if not city:
raise HTTPException(status_code=404, detail=f"City with ID {city_id} not found")
weather_data = get_weather_history_by_city(db, city_id, skip=skip, limit=limit)
return {"city": city, "weather_data": weather_data}

19
app/core/config.py Normal file
View File

@ -0,0 +1,19 @@
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# API Settings
API_V1_STR = "/api/v1"
PROJECT_NAME = "Weather Data API"
# OpenWeatherMap Settings
OPENWEATHERMAP_API_KEY = os.getenv("OPENWEATHERMAP_API_KEY", "bd5e378503939ddaee76f12ad7a97608")
OPENWEATHERMAP_BASE_URL = "https://api.openweathermap.org/data/2.5"
# Database Settings
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"

13
app/db/base.py Normal file
View File

@ -0,0 +1,13 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import SQLALCHEMY_DATABASE_URL
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

8
app/db/session.py Normal file
View File

@ -0,0 +1,8 @@
from app.db.base import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

1
app/models/__init__.py Normal file
View File

@ -0,0 +1 @@
from app.models.weather import City, WeatherData

35
app/models/weather.py Normal file
View File

@ -0,0 +1,35 @@
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from app.db.base import Base
class City(Base):
__tablename__ = "cities"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
country = Column(String)
latitude = Column(Float)
longitude = Column(Float)
created_at = Column(DateTime, default=datetime.utcnow)
weather_data = relationship("WeatherData", back_populates="city")
class WeatherData(Base):
__tablename__ = "weather_data"
id = Column(Integer, primary_key=True, index=True)
city_id = Column(Integer, ForeignKey("cities.id"))
temperature = Column(Float)
feels_like = Column(Float)
humidity = Column(Integer)
pressure = Column(Integer)
wind_speed = Column(Float)
wind_direction = Column(Integer)
description = Column(String)
weather_main = Column(String)
weather_icon = Column(String)
timestamp = Column(DateTime, default=datetime.utcnow)
city = relationship("City", back_populates="weather_data")

5
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,5 @@
from app.schemas.weather import (
City, CityCreate, CityBase,
WeatherData, WeatherDataCreate, WeatherDataBase,
WeatherResponse, CityWeather, CityQuery
)

53
app/schemas/weather.py Normal file
View File

@ -0,0 +1,53 @@
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional, List
class CityBase(BaseModel):
name: str
country: str
latitude: float
longitude: float
class CityCreate(CityBase):
pass
class City(CityBase):
id: int
created_at: datetime
class Config:
orm_mode = True
class WeatherDataBase(BaseModel):
temperature: float
feels_like: float
humidity: int
pressure: int
wind_speed: float
wind_direction: int
description: str
weather_main: str
weather_icon: str
class WeatherDataCreate(WeatherDataBase):
city_id: int
class WeatherData(WeatherDataBase):
id: int
city_id: int
timestamp: datetime
class Config:
orm_mode = True
class WeatherResponse(BaseModel):
city: City
current_weather: WeatherData
class CityWeather(BaseModel):
city: City
weather_data: List[WeatherData]
class CityQuery(BaseModel):
city: str = Field(..., description="City name")
country: Optional[str] = Field(None, description="Country code (ISO 3166-1 alpha-2)")

152
app/services/weather.py Normal file
View File

@ -0,0 +1,152 @@
import httpx
from datetime import datetime
from sqlalchemy.orm import Session
from fastapi import HTTPException
from app.core.config import OPENWEATHERMAP_API_KEY, OPENWEATHERMAP_BASE_URL
from app.models.weather import City, WeatherData
from app.schemas.weather import CityCreate, WeatherDataCreate
async def get_weather_by_city_name(city_name: str, country_code: str = None):
"""
Get current weather data from OpenWeatherMap API by city name
"""
params = {
"q": f"{city_name},{country_code}" if country_code else city_name,
"appid": OPENWEATHERMAP_API_KEY,
"units": "metric"
}
async with httpx.AsyncClient() as client:
response = await client.get(f"{OPENWEATHERMAP_BASE_URL}/weather", params=params)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code,
detail=f"Error from OpenWeatherMap: {response.json().get('message', 'Unknown error')}")
return response.json()
async def get_weather_by_coordinates(lat: float, lon: float):
"""
Get current weather data from OpenWeatherMap API by coordinates
"""
params = {
"lat": lat,
"lon": lon,
"appid": OPENWEATHERMAP_API_KEY,
"units": "metric"
}
async with httpx.AsyncClient() as client:
response = await client.get(f"{OPENWEATHERMAP_BASE_URL}/weather", params=params)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code,
detail=f"Error from OpenWeatherMap: {response.json().get('message', 'Unknown error')}")
return response.json()
def create_or_update_city(db: Session, owm_data: dict):
"""
Create or update city in the database
"""
# Check if city already exists
city = db.query(City).filter(
City.name == owm_data["name"],
City.latitude == owm_data["coord"]["lat"],
City.longitude == owm_data["coord"]["lon"]
).first()
if not city:
# Create new city
city_data = CityCreate(
name=owm_data["name"],
country=owm_data["sys"]["country"],
latitude=owm_data["coord"]["lat"],
longitude=owm_data["coord"]["lon"]
)
city = City(
name=city_data.name,
country=city_data.country,
latitude=city_data.latitude,
longitude=city_data.longitude
)
db.add(city)
db.commit()
db.refresh(city)
return city
def save_weather_data(db: Session, city_id: int, owm_data: dict):
"""
Save weather data to database
"""
weather_data = WeatherDataCreate(
city_id=city_id,
temperature=owm_data["main"]["temp"],
feels_like=owm_data["main"]["feels_like"],
humidity=owm_data["main"]["humidity"],
pressure=owm_data["main"]["pressure"],
wind_speed=owm_data["wind"]["speed"],
wind_direction=owm_data["wind"]["deg"],
description=owm_data["weather"][0]["description"],
weather_main=owm_data["weather"][0]["main"],
weather_icon=owm_data["weather"][0]["icon"]
)
db_weather_data = WeatherData(
city_id=weather_data.city_id,
temperature=weather_data.temperature,
feels_like=weather_data.feels_like,
humidity=weather_data.humidity,
pressure=weather_data.pressure,
wind_speed=weather_data.wind_speed,
wind_direction=weather_data.wind_direction,
description=weather_data.description,
weather_main=weather_data.weather_main,
weather_icon=weather_data.weather_icon,
timestamp=datetime.utcnow()
)
db.add(db_weather_data)
db.commit()
db.refresh(db_weather_data)
return db_weather_data
async def get_and_save_weather(db: Session, city_name: str, country_code: str = None):
"""
Get weather data from OpenWeatherMap API and save to database
"""
# Get weather data from OpenWeatherMap
owm_data = await get_weather_by_city_name(city_name, country_code)
# Create or update city
city = create_or_update_city(db, owm_data)
# Save weather data
weather_data = save_weather_data(db, city.id, owm_data)
return {"city": city, "current_weather": weather_data}
def get_city_by_id(db: Session, city_id: int):
"""
Get city by ID
"""
return db.query(City).filter(City.id == city_id).first()
def get_cities(db: Session, skip: int = 0, limit: int = 100):
"""
Get all cities
"""
return db.query(City).offset(skip).limit(limit).all()
def get_weather_history_by_city(db: Session, city_id: int, skip: int = 0, limit: int = 100):
"""
Get weather history for a specific city
"""
return db.query(WeatherData).filter(
WeatherData.city_id == city_id
).order_by(WeatherData.timestamp.desc()).offset(skip).limit(limit).all()

44
main.py Normal file
View File

@ -0,0 +1,44 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.api import api_router
from app.api.health import router as health_router
from app.core.config import API_V1_STR, PROJECT_NAME
from app.db.base import Base, engine
# Create database tables
Base.metadata.create_all(bind=engine)
app = FastAPI(
title=PROJECT_NAME,
description="API for retrieving weather data from OpenWeatherMap",
version="0.1.0",
)
# Set up CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(api_router, prefix=API_V1_STR)
app.include_router(health_router)
@app.get("/", tags=["root"])
def root():
"""
Root endpoint
"""
return {
"message": "Welcome to the Weather Data API",
"docs": "/docs",
"redoc": "/redoc"
}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi==0.103.1
uvicorn==0.23.2
sqlalchemy==2.0.20
pydantic==2.3.0
alembic==1.12.0
httpx==0.24.1
python-dotenv==1.0.0