Python rest API client

In the example we will connect to weather API to get temperature by city name using Requests.  We will use Flask and Jinja to render HTML form and the result.

Register and get API key at openweathermap.org

Create files:

main.py

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/temperature', methods=['POST'])
def temperature():
    city = request.form['city']

    r = requests.get('http://api.openweathermap.org/data/2.5/weather?APPID=4033281fcb0c091ad673d88f7a486808&q='+city+'&units=metric')
    json_object = r.json()
    temp = json_object['main']['temp']
    return render_template('temperature.html', temp=temp)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

templates/index.html

<!doctype html>
<html>
    <head>
        <title>Request example</title>
    </head>
    <body>
    <form action="/temperature" method="post">
        City: <input type="text" name="city">
        <input type="submit">
    </form>
    </body>
</html>

templates/temperature.html

<!doctype html>
<html>
<head>
    <title>Current Temperature</title>
</head>
    <body>
        <h1>The current temperature (C) is: {{temp}} degrees.</h1>
    </body>
</html>

Run. And navigate to localhost:5000

rest-api-input

temp-result

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s