Creating REST Service Using Flask And Python

Introduction

Flask is a very famous micro web framework written in Python. It was created by Armin Ronacher. It is based on the Werkzeug WSGI toolkit and Jinja2 template engine. It is very simple, flexible and provides fine-grained control. 

 
In this article, I will explain how to create a REST service by using Flask and Python.

Steps to Create REST Service

Install Flask by using the command prompt like below.
 
 pip3 install Flask
 
Create three Python files.
 
 
Here, I have created two Service files named AccountAPI and Balance.
 
AccountAPI.py
 
Python code in AccountAPI.py Service.
  1. from flask import Blueprint  
  2. import json  
  3.   
  4. account_api = Blueprint('account_api', __name__)  
  5.  
  6. @account_api.route("/account")  
  7. def accountList():  
  8.     return "list of accounts"  
  9.  
  10. @account_api.route("/names")  
  11. def namesList():  
  12.     my_json_string = json.dumps({'key1''Ram''key2''val2'})  
  13.     return my_json_string  
Balance.py
 
Python code in Balance.py Service.
  1. from flask import Blueprint  
  2. import json  
  3.   
  4. balance_api = Blueprint('balance_api', __name__)  
  5.  
  6. @balance_api.route("/balance")  
  7. def getBalance():  
  8.     return "list of balance"  
Main.py
 
This file defines the service end-point details and runs the server.
  1. from flask import Flask  
  2. from AccountAPI import account_api  
  3. from Balance import balance_api  
  4.   
  5. app = Flask(__name__)  
  6. app.register_blueprint(account_api, url_prefix='/accounts')  
  7. app.register_blueprint(balance_api, url_prefix='/balances')  
  8.  
  9. @app.route("/")  
  10. def hello():  
  11.     return "Hello World!"  
  12.   
  13. if __name__ == "__main__":  
  14.     app.run()  
Now, execute the code like below. Type the following command in command prompt.
 
python Main.py
 
Then, it will start the execution.

 
 
Open the browser and type the URL.
 
http://127.0.0.1:5000/accounts/names
 
It will give an output like below.
 

Finally, your services are deployed using Flask and Python 3.5. I have uploaded the complete zipped code for more details.
 
Conclusion

Flask is a very powerful and easy framework developed in Python for the deployment of REST services.

Up Next
    Ebook Download
    View all
    Python
    Read by 0 people
    Download Now!
    Learn
    View all