How to Create a RESTful API using Python and Flask - STEEMIT SCHOOL OF CODE

in #utopian-io6 years ago

restfulsteem.jpg

API
API Development in Python is as a matter of fact easy task. This tutorial will show you how to incorporate an integral REST API in Python with the Flask Framework.
REST APIs are pretty essentially everywhere. They are the standard rule of thumb to expose databases to clients and bright at which point to develop a REST API is a requirement at all layers of the stack.
There are profuse reasons therefore you should learn to transpire REST APIs in Python. If you are sleek to API development, previously learning how to develop a REST API, will bolster you to showcase yourself to the industry.

What does RESTful API mean ?
REST is an acronym for REpresentational State Transfer which is an architectural style, and an approach to communications that is usually used in the development of Web application and services. The use of REST is usually suitable over the much denser SOAP (Simple Object Access Protocol) style because REST does not leverage as much bandwidth, which makes it a better fit for use over the Internet. The SOAP approach requires writing or using a provided server program (to serve data) and a client program (to request data).
What this means is when using SOAP api when the client wants to send data to the server it combines the data with the soap standards which makes the data very large and unsuitable for the internet unlike RESTful the data is sent as it normal size virtually no increment in the size of the data.

Tools Required to build a RESTful API:
• Python
• Flask
• Flask-SQLAlchemy
• Flask-Restful
• SQlite3
• Jsonpify

Download the dataset from the Employees and Tracks Details (http://www.sqlitetutorial.net/sqlite-sample-database/) and extract in your project folder named ‘python_rest’. Database name is “chinook.db”
After download, make a file named server.py in the python_rest folder. This file will contain the API Definitions and Flask Code.
If you are on a windows pc navigate to the python_rest folder and install python virtual environment using the command pip install virtualenv, also install flask using pip install flask, install jsonpify using pip install flask-jsonpify, also pip install flask-sqlalchemy, and finally pip install flask-restful.

Screenshot (132).png
REST has got 4 options
• GET
• PUT
• POST
• DELETE
We will deal with GET and you will get how other works.
Before you start building or coding connect to the database.

Screenshot (133).png

Everything is set and all we need to do is code it. we begin to expose employees data and tracks data from database and also add a query operator on employees where employee’s details is searched and fetched by EmployeeID.

The Code:
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
from flask.ext.jsonpify import jsonify

db_connect = create_engine('sqlite:///chinook.db')
app = Flask(name)
api = Api(app)

class Employees(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select * from employees") # This line performs query and returns json result
return {'employees': [i[0] for i in query.cursor.fetchall()]} # Fetches first column that is Employee ID

class Tracks(Resource):
def get(self):
conn = db_connect.connect()
query = conn.execute("select trackid, name, composer, unitprice from tracks;")
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return jsonify(result)

class Employees_Name(Resource):
def get(self, employee_id):
conn = db_connect.connect()
query = conn.execute("select * from employees where EmployeeId =%d " %int(employee_id))
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return jsonify(result)

api.add_resource(Employees, '/employees') # Route_1
api.add_resource(Tracks, '/tracks') # Route_2
api.add_resource(Employees_Name, '/employees/<employee_id>') # Route_3

if name == 'main':
app.run(port='5002')

After deploying the code there will be there tracks created which are:
• Show details of all employees in the database
• Show track details
• Show details relating to specific employee.

Screenshot (134).png
Screenshot (135).png

Screenshot (136).png

Voila we have created a RESTful API, easy peasy, you can always add support for PUT, DELETE, POST.
Thank you for your time. use the comment box to ask questions.

Sort:  

if there is any help needed in setting this up, please do indicate

This isn't how utopian contribution should be made.

Follow this link to learn more
to contribute, please follow this link https://steemit.com/utopian-io/@utopian-io/utopian-now-contributions-are-welcome