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.
Table of Contents
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.
How To Check Python and pip Version
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
How To Install flask and requests Package
install python flask framework and requests package using below command :-
pip install flask pip install requests
Python Hello API Example Code
Now We will cd
into the /hello-api
folder.Created new hello.py
file into this folder.
Created API To Consume HTTP GET Call
We will write below code into hello.py
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 –
Run Python Application
c:/python-test/hello-api> py api.py
Test Python Flask API
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.