Skip to main content

Flask

Enhanced Advanced

Flask is a lightweight Python WSGI web application framework that is widely used for creating APIs.

Deploying

Use the Posit CLI to deploy Flask APIs.

Terminal
posit connect deploy api -n myServer MyApiPath/

When deploying a Flask API, ensure that you specify the correct entrypoint for the specific app you are deploying. The example applications in this section have their source code in a file named app.py, and within that file, the Flask 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 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.

Examples

There are many packages available to help improve your Flask API.

If your API does not define a GET / route, Connect looks for API documentation at these paths, in this order:

  • /docs
  • /apidocs
  • /ui
  • /swagger

If Connect finds one of these paths, it redirects GET / to that path. If Connect does not find any of these paths, it shows a placeholder page. To replace the placeholder page, add a GET / route to your API:

app.py
from flask import Flask

app = Flask(__name__)


@app.get("/")
def index():
    return {"status": "ok"}

When you use a package that generates API documentation, follow the guidance from the package maintainers, especially about version usage and security.

Requirements

The example application below is a read-only API for listing and fetching greetings for a small number of languages by locale name. The db gets its values from a greetings.json file with this format:

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

You must create and include this greetings.json in the example below.

APIFlask

The APIFlask package is a framework for building web APIs, based on Flask. It generates an OpenAPI specification from your routes and schemas.

By default, APIFlask serves an interactive API documentation page at GET /docs. Connect redirects GET / to that page.

A simplified APIFlask example looks like this:

app.py
# -*- coding: utf-8 -*-

import json

from apiflask import APIFlask, Schema, abort
from apiflask.fields import String

app = APIFlask(__name__, title="Greetings API", version="0.1.0")
db = json.load(open("greetings.json"))


class Greeting(Schema):
    lang = String(required=True, metadata={"description": "Language of the Greeting"})
    text = String(required=True, metadata={"description": "Text of the Greeting"})


@app.get("/greetings/")
@app.output(Greeting(many=True))
def list_greetings():
    return [{"lang": lang, "text": text} for lang, text in sorted(db.items())]


@app.get("/greetings/<string:lang>")
@app.output(Greeting)
def get_greeting(lang):
    if lang not in db:
        abort(404)
    return {"lang": lang, "text": db[lang]}

if __name__ == '__main__':
    app.run(debug=True)
requirements.txt
APIFlask

Use posit connect to deploy this example by specifying the apiflask-example directory containing app.py, greetings.json, and requirements.txt:

Terminal
posit connect deploy api \
    -n <saved server name> \
    --entrypoint app:app \
    ./apiflask-example/

User meta-data

Flask APIs can access the username and the names of the groups of the current logged in user by parsing the RStudio-Connect-Credentials request header.

Note

Your Flask API should access the RStudio-Connect-Credentials header value via the flask.request object’s headers property. This value is populated from the HTTP_RSTUDIO_CONNECT_CREDENTIALS environment variable present in the underlying WSGI environ.

This simple Flask API defines a /hello route that greets the arriving user.

app.py
# -*- coding: utf-8 -*-
import json

from flask import Flask, request

app = Flask(__name__)


def get_credentials(req):
    """
    Returns a dict containing "user" and "groups" information populated by
    the incoming request header "RStudio-Connect-Credentials".
    """
    credential_header = req.headers.get("RStudio-Connect-Credentials")
    if not credential_header:
        return {}
    return json.loads(credential_header)


@app.route("/hello")
def hello():
    user_metadata = get_credentials(request)
    username = user_metadata.get("user")
    if username is None:
        return {"message": "Howdy, stranger."}
    return {"message": f"So nice to see you, {username}."}

if __name__ == '__main__':
    app.run(debug=True)

User and group uniqueness

Most environments have unique usernames where each user identifies a single user and groups the name of the groups the user is a member of.

However, in large organizations with hundreds of users and groups, this may not be true. See the Admin Guide sections Credentials for Content for more information.