Skip to content

Instantly share code, notes, and snippets.

@vpnwall-services
Last active May 14, 2018 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vpnwall-services/06d274648bbab6039c87a6aaf1b3a27c to your computer and use it in GitHub Desktop.
Save vpnwall-services/06d274648bbab6039c87a6aaf1b3a27c to your computer and use it in GitHub Desktop.
[Python Rest API] Python example for building an API #linux #python #json #api
#!/bin/bash
cd /opt
mkdir sqlite3-databases ; cd sqlite3-databases
wget http://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip
unzip chinook.zip ; rm chinook.zip
virtualenv venv
source venv/bin/activate
pip install flask flask-jsonpify flask-sqlalchemy flask-restful
pip freeze
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
from flask import jsonify
db_connect = create_engine('sqlite:////opt/sqlite3-databases/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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment