Automated Action 6705b7a5e2 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)
2025-05-12 13:51:42 +00:00

85 lines
2.3 KiB
Python

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}