Wednesday, 6 March, 2019 UTC


Summary

This tutorial help to consume rest api using Python3 and flask.I got a change to work with python language. We will use python 3 and flask to create api wrapper.This flask application will consume sample rest api and return json data.
The Flask is microframework which is top on the Python.I am assuming virtualenv installed in your system, if not then you can download it from https://pypi.python.org/pypi/virtualenv.The request package help to create HTTP request to get response.
Let’s Create API Using Python and Flask
I am using windows, so i ll demonstrate step by step tutorial based on windows.Let’s create /hello-api folder, Now open cmd window.
We will click the Start menu icon and type cmd into the search box, then press Enter.Once your command line is open, enter these commands:
python --version
pip --version
install python flask framework and requests package using below command :-
pip install flask
pip install requests
cd into the /hello-api folder
Now create hello.py file into and write below code into this file –
from flask import Flask
from flask_restful import Resource, Api
from flask_cors import CORS
import requests

app = Flask(__name__)
CORS(app) ## To allow direct AJAX calls

@app.route('/employee', methods=['GET'])
def home():
    r = requests.get('http://dummy.restapiexample.com/api/v1/employees')

    return r.json()

if __name__ == '__main__':
   app.run(debug = True)
I have imported flask and flask_restful package from Flask framework, Also added requests package to create HTTP request.The flask_cors package help to remove Cross-Origin Resource Sharing (CORS), Now run app using below command –
c:/python-test/hello-api> py api.py
Now open browser and type http://localhost:5000/employee and press enter, You will get json data of all employees.The port 500 is the default port of python application.
The post Consuming a RESTful API with Python and Flask appeared first on Rest Api Example.