1
Write a post

Building a Basic RestFul API in Python

Published Feb 13, 2017
Building a Basic RestFul API in Python

Introduction

API Development in Python is a very easy task. This tutorial will help you to create a basic REST API in Python with the Flask Framework.

REST APIs are pretty much everywhere. They are the standard method to expose databases to clients and knowing how to develop a REST API is a necessity at all layers of the stack.

There are many reasons why you should learn to develop REST APIs in Python. If you are new to API development, then learning how to develop a REST API, will help you to showcase yourself to the industry.

What is REST API ?

REST (REpresentational State Transfer) is an architectural style, and an approach to communications that is often used in the development of Web services. The use of REST is often preferred over the more heavyweight 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).

You will get it more cleared by this picture.
soapvsrest.jpg

Stuffs we require to build our first REST API

  • Python
  • Flask
  • Flask-SQLAlchemy
  • Flask-Restful
  • SQlite3
  • Jsonify

Let the Code Begin

Download the dataset from the Employees and Tracks Details and extract in your project folder named 'python_rest'. Database name is "chinook.db"

Once downloaded, make a file named server.py in the python_rest folder. This file will contain the API Definitions and Flask Code.
Screen Shot 2017-02-13 at 11.17.52.png

Now, we create a basic virtual environment for Python2.7 and install the packages after it's activation.

$ virtualenv venv
$ source venv/bin/activate
$ pip install flask flask-jsonpify flask-sqlalchemy flask-restful
$ pip freeze

Screen Shot 2017-02-13 at 11.23.35.png

Let's create the basic GET API

REST has got 4 options

  • GET
  • PUT
  • POST
  • DELETE
    We will deal with GET and you will get how other works 😃

Before the code, connect yourself to database.
Screen Shot 2017-02-13 at 11.30.36.png

Now everything being set up, we begin the code of exposing 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 is:

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')
     

There will be three routes created :

It is simple to create a API. You can also add support to PUT,POST and DELETE on data too.
GitHub link is given below. Fork, Clone and add the supports and ace me back the Pull Requests 😃

Project Link: https://github.com/sagaragarwal94/python_rest_flask

Resources


Questions / Want to learn more .Hit me up ? Book a session with me 😃

Discover and read more posts from Sagar Chand Agarwal
get started
Enjoy this post?

Leave a like and comment for Sagar

22
14
14Replies
Rishikesh Agrawani
6 days ago

Nice Article.

Mehdi
10 days ago

next time when you wanted to Copy script Code from another Person tray to change it or Improve it

https://impythonist.wordpress.com/2015/07/12/build-an-api-under-30-lines-of-code-with-python-and-flask/

Sagar Chand Agarwal
10 days ago

I guessed you have read the current blog and then followed the repository too. I made sure the purpose of this code in the markdown file too. Well in event of changing, why not supply a PR ?

Roshni Kumari Gupta
25 days ago

can u help me with pyDal .i have to write API in python using pyDal.but how to install pyDal i dont know

Sagar Chand Agarwal
10 days ago

Saw the message now ? What is the issue you are facing here ? Or is it solved.

Show more replies

Get curated posts in your inbox

Learn programming by reading more posts like this