preface

Building an API in Python is a very simple task. This tutorial will help you write basic REST apis in Python using the Flask framework

REST apis are almost everywhere. They are standard ways of presenting data to clients, and understanding how to develop REST apis is essential for all developers, right

There are many reasons to learn to develop REST apis using Python. If you are new to API development, learning how to develop REST apis will help you excel in your work.

What is a REST API?

Representational State Transfer (REST), an architectural style, is a communication method commonly used for Web services development. REST is generally more popular than the heavier SOAP (Simple Object Access Protocol) because REST does not consume much bandwidth, making it more suitable for use in scenarios where there is a lot of network traffic. The SOAP approach requires writing or using the provided server program (to provide data) and client program (to request data)

The picture below will help you understand

Tools needed to build REST apis

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

Start coding

Download the data set from Employees and Tracks Details and put it in a project folder called “Python Rest” and name the database “chinook.db”

Once the download is complete, create a server.py file in the PYTHon_rest directory, where we will later write API definitions and Flask code.

Next, we create the virtual environment using PYTHon2.7 and install the dependent libraries:

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

REST has four methods

  • GET
  • PUT
  • POST
  • DELETE

Before you start writing code, make sure you can connect to the database properly:

Now that everything is set up, we begin to expose the code for employee data and track the data from the database, as well as adding a query operator about employees whose details are searched and retrieved by EmployeeID

With that in place, we can start writing code to get employee data,

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") Find data from database
        return {'employees': [i[0] for i in query.cursor.fetchall()]} Get the data and return it

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')
Copy the code

The above code creates three routes:

  • http://127.0.0.1:5002/employeesReturns the ids of all users in employees in the database
  • http://127.0.0.1:5002/tracksView details for all tracks tables
  • http://127.0.0.1:5002/employees/8Return the user with employees ID 8

Creating the API in this article is simple. You can also perform PUT, POST, and DELETE operations on data.


Via: www.codementor.io/sagaragarwa…

Author: [Agarwal](Project Link: github.com/sagaragarwa…) Translator: Alex1996a