HomeBack-End & DatabaseFlask RestAPI with requests

Flask RestAPI with requests

Introduction:

Requests is a Python module that you can use to send all kinds of HTTP requests. It is an easy-to-use library with a lot of features ranging from passing parameters in URLs to sending custom headers and SSL Verification.

we can use requests library very easily like this.

import requests
req = requests.get('https://www.excellencetechnologies.in/')

Now let’s install the requests library.

How to Install Requests:

You can make use of pip, easy_install, or tarball package managers. I am using PIP to install the requests library.

 
pip install requests

Let,s we do something interesting using requests library . we make a weather app using requests library or open weather API.

We can access weather data using openweathermap API. So give a quick look on openweathermap API.

Step 1: SignUp Process

1. Go to openweathermap and signup yourself.
2. Then you will get an API key on your registered email.

Now we check our openweathermap API key. First, we do one thing simple copy weather API URL from our email and paste it on the URL bar.

hmm, our API key it worked but it gave very complex data. It makes us irritating. So we make an API with requests library. For getting data in a format.

Lets start first import requests library and write a code.

 
import requests
from flask import Flask,jsonify,request
import json

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/city',methods=['POST'])
def index():
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID=6ae9e1b36a243b7412e5fa2d0c42e6ab'

city = request.json.get("city")
result = requests.get(url.format(city)).json()

weather = {
'city': city,
'temperature': result['main']['temp'],
'description': result['weather'][0]['description'],
}
return jsonify(weather)

Now test our code using postman.

see we got only specific fields not got all complex data. finally, we have done this very easily using the requests library.

That’s fine but we update our current app. Now we do one thing we get the device current location and then get the weather details.

For this we need to get the ipstack API key so follow steps.

Step 2: SignUp process

1. Go to https://ipstack.com/ and signup yourself.
2. Then you will get an API key.

Now we have a location tracking API key . we make a route for get device current location weather.

Step 3: Make route

Now we get our device current location. For this, we use our another route ‘/location/ 

 
@app.route('/location',methods=['GET'])
def by_location():
send_url = "http://api.ipstack.com/check? access_key=fdc0c9d1b7b5a590fb8e16f0f0dcf352"
geo_req = requests.get(send_url)
geo_json = json.loads(geo_req.text)
city = geo_json['city']


url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID=6ae9e1b36a243b7412e5fa2d0c42e6ab'
result = requests.get(url.format(city)).json()
weather = {
'city': city,
'temperature': result['main']['temp'],
'description': result['weather'][0]['description'],
}
return jsonify(weather)

Now we test our code in postman.And we got this in response.

Now by the use of requests library and API,s we got weather by the current device location. In this case, we don’t need to give any city name. It automatically detects the city name.

Here is the entire final code for reference .

 
import requests
from flask import Flask,jsonify,request
import json

app = Flask(__name__)
app.config['DEBUG'] = True


#Api for get weather by city name
@app.route('/city',methods=['POST'])
def index():
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID=6ae9e1b36a243b7412e5fa2d0c42e6ab'

city = request.json.get("city")
result = requests.get(url.format(city)).json()

weather = {
'city': city,
'temperature': result['main']['temp'],
'description': result['weather'][0]['description'],
}
return jsonify(weather)



#Api for get weather by current location
@app.route('/location',methods=['GET'])
def by_location():
send_url = "http://api.ipstack.com/check?access_key=fdc0c9d1b7b5a590fb8e16f0f0dcf352"
geo_req = requests.get(send_url)
geo_json = json.loads(geo_req.text)
city = geo_json['city']


url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID=6ae9e1b36a243b7412e5fa2d0c42e6ab'
result = requests.get(url.format(city)).json()
weather = {
'city': city,
'temperature': result['main']['temp'],
'description': result['weather'][0]['description'],
}
return jsonify(weather)


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

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: