Server App for APIs

I found a brilliant script to handle API requests. I noticed three elements here: it contains a server process, it is able to receive a call and it is able to return results.

The script:

import flask
from flask import request, jsonify
import pyodbc
import pandas as pd
app = flask.Flask(name)
app.config["DEBUG"] = True
def dict_factory(cursor, row):
  d = {}
  for idx, col in enumerate(cursor.description):
    d[col[0]] = row[idx]
  return d
@app.route('/', methods=['GET'])
def home():
  return '''Distant Reading Archive'''
@app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
  connStr =       pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=****')
  cursor = connStr.cursor()
  data = []
  rows = cursor.execute('SELECT * FROM books;').fetchall()
  for row in rows:
    data.append([x for x in row])
  cursor.close()
  connStr.close()
  return jsonify(data)
@app.errorhandler(404)
def page_not_found(e):
  return "404 The resource could not be found.", 404
@app.route('/api/v1/resources/books', methods=['GET'])
def api_filter():
  query_parameters = request.args
  id = query_parameters.get('id')
  published = query_parameters.get('published')
  author = query_parameters.get('author')
  query = "SELECT * FROM books WHERE"
  to_filter = []
  if id:
    query += ' id=? AND'
    to_filter.append(id)
  if published:
    query += ' published=? AND'
    to_filter.append(published)
  if author:
    query += ' author=? AND'
    to_filter.append(author)
  if not (id or published or author):
    return page_not_found(404)
  query = query[:-4] + ';'
  connStr = pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=*****')
  cursor = connStr.cursor()
  data = []
rows = cursor.execute(query, to_filter).fetchall()
for row in rows:
  data.append([x for x in row])
cursor.close()
connStr.close()
return jsonify(data)
app.run()

This API can be called by two different calls:

http://127.0.0.1:5000/api/v1/resources/books?author=Connie+Willis 

or

 http://127.0.0.1:5000/api/v1/resources/books/all

It can be see in the code what happens. If we call http://127.0.0.1:5000/api/v1/resources/books/all, we see that a function is used that is provided after the definition of “/api/v1/resources/books/all”. In that function, we a sql is fired that is “SELECT * FROM books;”. We see that the query results are returned as a json file.

As it is a GET call, the results are simply returned to the client.

If we call “127.0.0.1:5000/api/v1/resources/books?author=Connie+Willis”, we see what happens after the definition /api/v1/resources/books, in combination with some arguments. The arguments are provided after the ? mark. We see that parameter author is used. When that parameter is used, a query is used that is formulated as “SELECT * FROM books WHERE author = Connie+Willis”