DEV Community

Cover image for Forecast Your Weather With Python Script
Prakash Singh
Prakash Singh

Posted on

Forecast Your Weather With Python Script

What we are going to build ?
 → In order to check your place's weather. With the help of inbuilt libraries of python like requests, json and IPython. From "IPython" library , we use modules like "Image" and "display".

Step 1 : Importing Dependencies

import requests
import json
from IPython.display import Image, display
Enter fullscreen mode Exit fullscreen mode




Step 2 : Enter your api-key
 → You can use https://api.openweathermap.org/ and get your API key. So that, you will get access of data.

# api-key
appId="94*********************"
Enter fullscreen mode Exit fullscreen mode




Step 3 : Enter your place name

# place input
query=input("Enter Your Place to Check Weather : ")
Enter fullscreen mode Exit fullscreen mode




Step 4 : Make queries for URL
 → Here you can write more specific queries for URL.

# queries
unit="metric"
Enter fullscreen mode Exit fullscreen mode




Step 5 : Create Dynamic URL
 → Design your URL. With query variables and make sure that you are using api key or id.

# API url
url="https://api.openweathermap.org/data/2.5/weather?q="+f"{query}"+"&appid="+f"{appId}"+"&units="+f"{unit}"
Enter fullscreen mode Exit fullscreen mode




Step 6 : Send GET request and store response of URL hit

# get response from api-hit
response=requests.get(url,stream=True)
Enter fullscreen mode Exit fullscreen mode




Step 7 : Store data from response

# get data (in bytes form)
data=response.content
Enter fullscreen mode Exit fullscreen mode




Step 8 : Convert "bytes" format to json

# get json file from "bytes" type
jsn=json.loads(data.decode("utf-8"))
Enter fullscreen mode Exit fullscreen mode




Step 9 : Store important data from converted json file

# get temperature
temp=jsn["main"]["temp"]

# get weather icon
icon=jsn["weather"][0]["icon"]

# get weather description
weatherDesc=jsn['weather'][0]["description"]
Enter fullscreen mode Exit fullscreen mode




Step 10 : Send GET request and store response of URL to fetch Image

# get request with imageUrl to fetch png image
imageUrl="https://openweathermap.org/img/wn/"+f"{icon}"+"@2x.png"
response2=requests.get(imageUrl,stream=True)
Enter fullscreen mode Exit fullscreen mode




Step 11 : Display Outputs

# display png
display(Image(response2.content))

# display temperature
print(f"Temperature : {temp}°C (Degree Celcius)")

# display place name
print(f"Place : {query}")

# display weather description
print(f"Weather Description : {weatherDesc}")
Enter fullscreen mode Exit fullscreen mode

Sample Output :

Forecast-Weather


Github Link For Full Code : Click Here

Top comments (0)