FastAPI
FastAPI is a PythonASGI 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 Pythonasync functions, which allows multiple requests to be processed concurrently. This is useful when the response depends on the results of otherasync functions. For example, if you use an asynchronous database client to access a remote database, your endpoint function canawait 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 aGET / handler, Posit Connect will provide one that redirects toGET /docs.
Deploying
FastAPI and other ASGI-compatible APIs can be deployed with thersconnect-python package.
rsconnect deploy fastapi-n myServer MyApiPath/When deploying a FastAPI API, ensure that you specify the correctentrypoint for the specific app you are deploying. The example in this section has its source code in a file namedapp.py, and within that file, the FastAPI application object is namedapp. So the entrypoint specified here isapp:app. If the main source file or application object is named differently, you need to specify a different entrypoint so that Connect can locate the application object to serve. See the documentation onentrypoints for more information.
Examples
JSON example
The example application is aread-only API for listing and fetching greetings for a small number of languages by locale name, where thedb is populated from a file.
First, create a directory for the project:
mkdir fastapi-examplecd fastapi-exampleThen, create thisgreetings.json file:
{"ar":"آلو","bn":"হ্যালো","chr":"ᏏᏲ","en":"Hello","es":"Hola","sw":"هَبَارِ","zh":"你好"}and createapp.py which contains the API code:
# fastapi-example/app.py# -*- coding: utf-8 -*-import jsonfrom fastapiimport FastAPIfrom pydanticimport BaseModelfrom typingimport Listclass Greeting(BaseModel): lang:str text:strapp= FastAPI()db= json.load(open("greetings.json"))@app.get("/greetings", response_model=List[Greeting])asyncdef greetings():return [Greeting(lang=lang, text=text)for lang, textinsorted(db.items())]@app.get("/greetings/{lang}", response_model=Greeting)asyncdef greeting(lang:str="en"):return Greeting(lang=lang, text=db.get(lang))Deploy the example usingrsconnect-python:
rsconnect deploy fastapi\-n<saved server name>\--entrypoint app:app\ ./Test out the API usingcurl 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 anAPI key for authorization.
curl-X'GET'\<api endpoint>/greetings' \ -H 'accept: application/json' \ -H "Authorization: Key ${CONNECT_API_KEY}"HTML example
FastAPI is most commonly used to build JSON APIs. FastAPI can also be used to create APIs that respond with HTML. By returning HTML, you can make fully functional web applications with FastAPI. Content deployed this way still counts as an API content type, and is not considered interactive.
First, create a directory for the project:
mkdir fastapi-html-examplecd fastapi-html-exampleThe structure of the project will look like this:
.├── app.py├── requirements.txt├── static│ └── styles.css└── templates├── about.html├── base.html└── index.htmlFirst, create therequirements.txt file:
fastapiuvicorn[standard]jinja2rsconnect-pythonNext, create a virtual environment:
python-m venv .venvsource .venv/bin/activatepython-m pip install--upgrade pip wheel setuptoolspython-m pip install-r requirements.txtInapp.py, add the following code:
from fastapiimport FastAPI, Requestfrom fastapi.responsesimport HTMLResponsefrom fastapi.staticfilesimport StaticFilesfrom fastapi.templatingimport Jinja2Templatesapp= FastAPI()app.mount("/static", StaticFiles(directory="static"), name="static")templates= Jinja2Templates(directory="templates")@app.get("/", response_class=HTMLResponse)asyncdef get_index(request: Request):return templates.TemplateResponse("index.html", {"request": request })@app.get("/about", response_class=HTMLResponse)asyncdef get_about(request: Request, name:str="Posit"):return templates.TemplateResponse("about.html", {"request": request ,"name": name})Then, create the HTML files:
templates/base.html
<html><head> {% block head %}<link href="static/styles.css" rel="stylesheet"><title>{% block title %}{% endblock %} - My Connect App</title> {% endblock %}</head><body><div id="content">{% block content %}{% endblock %}</div></body></html>templates/index.html
{% extends "base.html" %}{% block title %}Home{% endblock %}{% block content %}<div><h1>Hello world</h1><p>This is a webapp built using FastAPI.</p><p>Check out the<a href="about">About</a> page for more info.</p></div>{% endblock %}templates/about.html
{% extends "base.html" %}{% block title %}About{% endblock %}{% block content %}<div><h1>About</h1><p>Welcome to the about page {{ name }}. We are glad you are here.</p><p>Click<a href="{{ request.headers['rstudio-connect-app-base-url'] }}/">here</a> to navigate back to the home page.</p></div>{% endblock %}For links to the root of the API (/), it is required to use{ request.headers['rstudio-connect-app-base-url'] }/. This is because Connect has an internal proxy that it uses to route traffic to different locations. The base URL of your application cannot be known ahead of time, but it can be determined at runtime from therstudio-connect-app-base-url header. For links that are not to the root, you can use relative links. For example, to link to the/about page, usehref=about.
Lastly, create thestatic/styles.css file for styling:
h1 {color:green;}To preview the application locally, run the following:
uvicorn app:app--reloadDeploy the example usingrsconnect-python:
rsconnect deploy fastapi\-n<saved server name>\--entrypoint app:app./To learn more about building web apps with FastAPI, see these resources:
User meta-data
FastAPI can access the username and the names of the groups of the current logged in user by parsing theRStudio-Connect-Credentials request header.
Your FastAPI should access theRStudio-Connect-Credentials header value via theHeader object in FastAPI. See theFastAPI documentation on headers for more details. The example below uses FastAPI’s dependency injection system so that the logic to get the current user is only defined once and can be reused by multiple endpoints. See theFastAPI documentation on dependency injection for more details.
User meta-data example
This simple FastAPI defines a/hello route that greets the arriving user.
import jsonfrom typingimport Annotatedfrom fastapiimport FastAPI, Header, Dependsfrom fastapi.responsesimport JSONResponsefrom pydanticimport BaseModel, Fieldapp= FastAPI()class UserMetadata(BaseModel): user:str groups:list[str]= Field(list)asyncdef get_current_user( rstudio_connect_credentials: Annotated[str|None, Header()]=None)-> UserMetadata|None:""" Get the user metadata from the RStudio-Connect-Credentials header and then parse the data into a UserMetadata object. """if rstudio_connect_credentialsisNone:returnNone user_meta_data= json.loads(rstudio_connect_credentials)return UserMetadata(**user_meta_data)@app.get("/hello")asyncdef get_hello(user=Depends(get_current_user))-> JSONResponse:""" Use FastAPIs dependency injection system to get the current user. """if userisNone:return {"message":"Howdy stranger!"}return {"message":f"So nice to see you,{user.user}!"}User and group uniqueness
Most environments have unique usernames where eachuser identifies a single user andgroups the name of the groups the user is a member of.
However, in large organizations with hundreds of users and groups, this might not be true. See theCredentials for Content section of the Connect Admin Guide for more information.
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 Connect). These frameworks have been validated for deployment in 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.


