File size: 1,238 Bytes
4a49187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

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"
@app.get("/")
def home():
    return {"message": "Welcome to the Weather Finder API"}
@app.get("/weather")
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}
@app.post("/weather")
def post_weather_endpoint(request: WeatherRequest):
    weather_info = get_weather(request.location)
    return {"location": request.location, "weather_info": weather_info}