weather_api.pyā¢2.94 kB
"""
FastAPI Weather Information Application
Provides weather information endpoints
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import random
from datetime import datetime
app = FastAPI(title="Weather Info API", version="1.0.0")
class WeatherResponse(BaseModel):
city: str
country: str
temperature: float
condition: str
humidity: int
wind_speed: float
description: str
timestamp: str
class WeatherRequest(BaseModel):
city: str
country: Optional[str] = None
# Mock weather data generator
def get_weather_data(city: str, country: Optional[str] = None) -> dict:
"""Generate mock weather data for a city"""
conditions = ["Sunny", "Cloudy", "Rainy", "Partly Cloudy", "Clear", "Overcast"]
descriptions = {
"Sunny": "Clear skies with bright sunshine",
"Cloudy": "Overcast with clouds covering the sky",
"Rainy": "Light to moderate rain expected",
"Partly Cloudy": "Some clouds with periods of sunshine",
"Clear": "Clear and pleasant weather",
"Overcast": "Heavy cloud cover"
}
# Use city name to generate consistent (but random) weather
random.seed(hash(city.lower()) % 1000)
condition = random.choice(conditions)
weather = {
"city": city,
"country": country or "Unknown",
"temperature": round(random.uniform(-10, 35), 1),
"condition": condition,
"humidity": random.randint(30, 90),
"wind_speed": round(random.uniform(0, 25), 1),
"description": descriptions[condition],
"timestamp": datetime.now().isoformat()
}
return weather
@app.get("/")
async def root():
return {
"message": "Weather Information API",
"endpoints": {
"/weather": "Get weather by city (POST or GET)",
"/health": "Health check"
}
}
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "weather-api"}
@app.post("/weather", response_model=WeatherResponse)
async def get_weather_post(request: WeatherRequest):
"""Get weather information for a city (POST)"""
try:
weather_data = get_weather_data(request.city, request.country)
return WeatherResponse(**weather_data)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching weather: {str(e)}")
@app.get("/weather", response_model=WeatherResponse)
async def get_weather_get(city: str, country: Optional[str] = None):
"""Get weather information for a city (GET)"""
try:
weather_data = get_weather_data(city, country)
return WeatherResponse(**weather_data)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching weather: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)