FastAPI

FastAPI is a Python ASGI web API framework.

FastAPI uses type annotations and Pydantic models to provide input validation and automatic API documentation using OpenAPI / Swagger.

Endpoints in FastAPI are Python async functions, which allows multiple requests to be processed concurrently. This is useful when the response depends on the results of other async functions. For example, if you use an asynchronous database client to access a remote database, your endpoint function can await the results of the database query. New requests can begin to be processed while earlier requests are awaiting their results.

The Swagger documentation is accessible via the /docs path in your API. If you do not define a GET / handler, Posit Connect will provide one that redirects to GET /docs.

Example FastAPI Swagger documentation.

Deploying

FastAPI and other ASGI-compatible APIs can be deployed with the rsconnect-python package.

rsconnect deploy fastapi -n myServer MyApiPath/

When deploying a FastAPI API, ensure that you specify the correct entrypoint for the specific app you are deploying. The example in this section has its source code in a file named app.py, and within that file, the FastAPI application object is named app. So the entrypoint specified here is app:app. If the main source file or application object is named differently, you will need to specify a different entrypoint so that Posit Connect can locate the application object to serve. See the documentation on entrypoints for more information.

Example

The example application is a read-only API for listing and fetching greetings for a small number of languages by locale name, where the db is populated from a file.

First, create a directory for the project:

mkdir fastapi-example
cd fastapi-example

Then, create this greetings.json file:

{
    "ar": "آلو",
    "bn": "হ্যালো",
    "chr": "ᏏᏲ",
    "en": "Hello",
    "es": "Hola",
    "sw": "هَبَارِ",
    "zh": "你好"
}

and create app.py which contains the API code:

# fastapi-example/app.py
# -*- coding: utf-8 -*-

import json
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List


class Greeting(BaseModel):
    lang: str
    text: str


app = FastAPI()
db = json.load(open("greetings.json"))


@app.get("/greetings", response_model=List[Greeting])
async def greetings():
    return [Greeting(lang=lang, text=text) for lang, text in sorted(db.items())]


@app.get("/greetings/{lang}", response_model=Greeting)
async def greeting(lang: str = "en"):
    return Greeting(lang=lang, text=db.get(lang))

Deploy the example using rsconnect-python:

rsconnect deploy fastapi \
    -n <saved server name> \
    --entrypoint app:app \
    ./

Test out the API using curl from the command line:

curl -X 'GET' \
  <api endpoint>/greetings' \
  -H 'accept: application/json'

If the API is only accessible to certain groups or users use an API Key for authorization.

curl -X 'GET' \
  <api endpoint>/greetings' \
  -H 'accept: application/json' \
  -H "Authorization: Key ${CONNECT_API_KEY}"

Other ASGI Frameworks

Although ASGI is a standard, frameworks differ in the configuration settings required to support being deployed behind a proxy server (as is the case for APIs deployed within Posit Connect). These frameworks have been validated for deployment in Posit Connect:

  • Quart is very similar to Flask, except that API endpoint functions are asynchronous.

  • Falcon is a Python framework that supports both synchronous (WSGI) and async (ASGI) APIs. When creating your API, you choose between synchronous and asynchronous operation.

  • Sanic is a fast asynchronous API framework for Python.