Weather API with Python (TUTORIAL).

Hi Guys,

In this tutorial we will be seeing how to create a Weather API which will tell the weather of the country which we give!. So it's super interesting project. Let's Get Started.

1.We will be using python-weather module to get the weather info and also we will be using asyncio because we will declare our getweather function as async funtion.

Code:

import python_weather

import asyncio 

2. We will create our function it's just like creating a normal function but with async keyword before declaring.

Code:

async def getweather():

Note: Here we are using async function instead of normal function because we are going to do more process and it must be waited and done as per order.

3. Next we will get the city name input from the user and we will create a client which will connect our script with the python-weather module.

Code:

    city = str(input("Enter the city Name: "))
    # declare the client. format defaults to metric system (celcius, km/h, etc.)
    client = python_weather.Client(format=python_weather.IMPERIAL)

4. next we will find the weather of the city which the user is given in the input. It's super simple to find the weather.

Code:

    weather = await client.find(city)

Here we are using await because we are saying the script to wait until the module fetches the weather of the city if this process is skipped then our Weather API will not work properly.

5. Next we will print the weather degree of the city.

Code:

    print("Current Weather in " + city + " is:" + " " + str(weather.current.temperature) + "'C")

6. Next we will close the client to stop our CPU utilization and internet.

Code: 

    await client.close()

7. Last step is to Call the function, but here we will loop the async function because to finish all the process inside the function.

Code:

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(getweather())

That's All You have created a Weather API which will fetch you the degree of the city.

See you in the next tutorial.

REFERENCE:

https://pypi.org/project/python-weather/