Fastapi Routes

Most canonical examples for fastapi use fastapi.FastAPI to instantiate an application. This notebook envisions a situation where an author has written several useful notebooks and they want to reuse as API’s. This is acheived with fastapi and importnb.

import requests, pandas, IPython

fastapi provides the fastapi.APIRouter to build bigger applications

app = __import__('fastapi').APIRouter()  # Typically __import__('fastapi').FastAPI()

user is an example endpoint that recieves Github information for a username.

@app.get('/user')
def user(name: str = 'tonyfast'):
    global id
    id = pandas.Series(requests.get(F'https://api.github.com/users/{name}').json())
    return id.to_dict()

__import__('requests_cache').install_cache('fastapi_routes') # Add a caching mechanism.

gists accesses the user’s gist.

@app.get('/gists')
def gists(pages: int = 2):
    global id, df
    globals().get('id', user())
    df = pandas.concat([pandas.DataFrame(requests.get(
        F'https://api.github.com/users/{id.login}/gists?page={i}').json()
                                        ) for i in range(1, pages)])
    return [x.to_dict() for n, x in df.iterrows()]

Use the base starlette library to customize to customize repsonses. For example, we return a pandas table.

@app.get('/table', response_class=__import__('starlette').responses.HTMLResponse)
def table(): return globals()['df'].to_html()

Running the application

  1. Running this notebook

    Under the right conditions this notebook can be executed as a standalone application using the code below.

if __name__ == '__main__' and '__file__' in globals():
    APP = __import__('fastapi').FastAPI()
    APP.include_router(app)
    __name__ == '__main__' and __import__('uvicorn').run(APP, host="0.0.0.0", port=8000)
  1. Running many notebooks with fastapi and uvicorn.

    Create an application level python file to aggregrate the fastapi.APIRouters into a unified application. Each endpoint is prefix by the module name.

__name__ == '__main__' and '__file__' not in globals() and IPython.display.Code(filename='main.py')
app = __import__('fastapi').FastAPI()
with __import__('importnb').Notebook():
    try: from . import __fastapi_routes
    except: import __fastapi_routes
app.include_router(__fastapi_routes.app, prefix=F"/{__fastapi_routes.__name__}")
__name__ == '__main__' and __import__('uvicorn').run(app, host="0.0.0.0", port=8000)
Written on September 29, 2019