Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, Query | |
from pydantic import BaseModel | |
import requests | |
from datetime import date | |
import uvicorn | |
app = FastAPI() | |
class WeatherRequest(BaseModel): | |
location: str | |
API_KEY = "d66b99384fc0495b9bb43946242607" | |
BASE_URL = "http://api.weatherapi.com/v1/current.json" | |
def get_weather(location): | |
params = { | |
"key": API_KEY, | |
"q": location, | |
"dt": date.today().isoformat() | |
} | |
response = requests.get(BASE_URL, params=params) | |
if response.status_code == 200: | |
data = response.json() | |
current = data['current'] | |
return f"Temperature: {current['temp_c']}°C, Condition: {current['condition']['text']}" | |
else: | |
return "Unable to fetch weather data" | |
def home(): | |
return {"message": "Welcome to the Weather Finder API"} | |
def get_weather_endpoint(location: str = Query(..., description="Location to get weather for")): | |
weather_info = get_weather(location) | |
return {"location": location, "weather_info": weather_info} | |
def post_weather_endpoint(request: WeatherRequest): | |
weather_info = get_weather(request.location) | |
return {"location": request.location, "weather_info": weather_info} | |
if __name__ == "__main__": | |
uvicorn.run(app, host="0.0.0.0", port=8000) |