DEV Community

Zhao Xinhao
Zhao Xinhao

Posted on • Edited on

Weather Query in Python

1.Install FastAPI and tools

bash
pip install fastapi uvicorn requests python-dotenv

2.Create a folder for project
Open terminal and run:

bash
mkdir Weather Query
cd Weather Query

3.Create a .envfile to store API key securely
Inside the Weather Query folder, create a new file named .env,open the file and add this line(we'll get the actual API key next):

plaintext
OPENWEATHER_API_KEY=your_api_key_here

4.Create main.py
Inside Weather Query, create a new file named main.py

python

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import requests
import os
from dotenv import load_dotenv

# Load API key from .env
load_dotenv()  # This looks for the .env file automatically
API_KEY = os.getenv("OPENWEATHER_API_KEY")  # Reads your key

app = FastAPI()

class CityRequest(BaseModel):
    city: str  # This defines what data your API expects

@app.post("/weather")
def get_weather(city: CityRequest):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city.city}&appid={API_KEY}&units=metric"
    response = requests.get(url)

    if response.status_code != 200:
        raise HTTPException(status_code=400, detail="City not found or API error")

    weather_data = response.json()
    return {
        "city": city.city,
        "temperature": weather_data["main"]["temp"],
        "weather": weather_data["weather"][0]["description"]
    }
Enter fullscreen mode Exit fullscreen mode

5.Start the FastAPI Server
In terminal(inside the Weather Query folder),run:
bash
uvicorn main:app --reload
Expected Output:
INFO: Uvicorn running on http://127.0.0.1:8000

6.Test the API in Browser
Open browser and go to http://localhost:8000/docs, find the POST / weather endpoint, click "Try it out", enter a city name(e.g., {"city": "Tokyo"}), click "Execute".

Expected Output:​​
{
"city": "Tokyo",
"temperature": 25.5,
"weather": "clear sky"
}

7.Try Errors
Enter an invalid city(e.g.,{"city": "Hogwarts"})

json
"detail": "City not found or API error"

8.Create weather.html And Add Basic Html Structure
html

<!DOCTYPE html>
<html>
<head>
    <title>Weather App</title>
</head>
<body>
    <h1>Weather Check</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

9.Add City Input and Button
html
<input type="text" id="city" placeholder="Enter city name">
<button onclick="getWeather()">Get Weather</button>
<div id="result"></div>

10.Add JavaScript to weather.html
html

<script>
    async function getWeather() {
        const city = document.getElementById("city").value;
        const response = await fetch("http://localhost:8000/weather", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ city: city })
        });
        const data = await response.json();
        if (data.detail) {
            document.getElementById("result").innerText = `Error: ${data.detail}`;
        } else {
            document.getElementById("result").innerHTML = `
                <p>City: ${data.city}</p>
                <p>Temperature: ${data.temperature}°C</p>
                <p>Weather: ${data.weather}</p>
            `;
        }
    }
</script>
Enter fullscreen mode Exit fullscreen mode

fetch():Calls FastAPI endpoint(POST /weather)with the city name.
response.json():Converts the API response to JSON.
Error Handling:Shows errors(e.g., "City not found")or displays weather data.
innerHTML:Inserts HTML into the result div.
async/await:Waits for the API call to finish before proceeding.

11.Serve the HTML File
Update main.py(FastAPI) to serve weather.html at the root URL(/):
python

# Lets FastAPI send a file(like weathter.html)as a response
from fastapi.responses import FileResponse

# Serve the HTML file at the root URL
@app.get("/")
def read_root():
    return FileResponse("weather.html")
Enter fullscreen mode Exit fullscreen mode

12.Run the Server and Check the Browser
uvicorn main:app --reload
go to http://localhost:8000/ ,you will see

Top comments (0)