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])
  return jsonify(data)
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'
  if published:
    query += ' published=? AND'
  if author:
    query += ' author=? AND'
  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])
return jsonify(data)

This API can be called by two different calls: 


It can be see in the code what happens. If we call, 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 “”, 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”