Skip to main content

A FastAPI + Pydantic extension for simplifying hypermedia-driven API development.

Project description

FastAPI-HyperModel

FastAPI-HyperModel is a FastAPI + Pydantic extension for simplifying hypermedia-driven API development. This module adds a new Pydantic model base-class, supporting dynamic href generation based on object data.

Installation

pip install fastapi-hypermodel

Basic Usage

Import HyperModel and optionally HyperRef

from fastapi import FastAPI

from fastapi_hypermodel import HyperModel, UrlFor, LinkSet

HyperModel will be your model base-class.

Create your basic models

We'll create two models, a brief item summary including ID, name, and a link, and a full model containing additional information. We'll use ItemSummary in our item list, and ItemDetail for full item information.

class ItemSummary(HyperModel):
    id: str
    name: str

class ItemDetail(ItemSummary):
    description: Optional[str] = None
    price: float

class Person(HyperModel):
    name: str
    id: str
    items: List[ItemSummary]

Create and attach your app

We'll now create our FastAPI app, and bind it to our HyperModel base class.

from fastapi import FastAPI

app = FastAPI()
HyperModel.init_app(app)

Add some API views

We'll create an API view for a list of items, as well as details about an individual item. Note that we pass the item ID with our {item_id} URL variable.

@app.get("/items", response_model=List[ItemSummary])
def read_items():
    return list(items.values())

@app.get("/items/{item_id}", response_model=ItemDetail)
def read_item(item_id: str):
    return items[item_id]

@app.get("/people/{person_id}", response_model=Person)
def read_person(person_id: str):
    return people[person_id]

@app.get("/people/{person_id}/items", response_model=List[ItemDetail])
def read_person_items(person_id: str):
    return people[person_id]["items"]

Create a model href

We'll now go back and add an href field with a special UrlFor value. This UrlFor class defines how our href elements will be generated. We'll change our ItemSummary class to:

class ItemSummary(HyperModel):
    name: str
    id: str
    href = UrlFor("read_item", {"item_id": "<id>"})

The UrlFor class takes two arguments:

endpoint

Name of your FastAPI endpoint function you want to link to. In our example, we want our item summary to link to the corresponding item detail page, which maps to our read_item function.

values (optional depending on endpoint)

Same keyword arguments as FastAPI's url_path_for, except string arguments enclosed in < > will be interpreted as attributes to pull from the object. For example, here we need to pass an item_id argument as required by our endpoint function, and we want to populate that with our item object's id attribute.

Create a link set

In some cases we want to create a map of relational links. In these cases we can create a LinkSet field describing each link and it's relationship to the object.

class Person(HyperModel):
    id: str
    name: str
    items: List[ItemSummary]

    href = UrlFor("read_person", {"person_id": "<id>"})
    links = LinkSet(
        {
            "self": UrlFor("read_person", {"person_id": "<id>"}),
            "items": UrlFor("read_person_items", {"person_id": "<id>"}),
        }
    )

Putting it all together

For this example, we can make a dictionary containing some fake data, and add extra models, even nesting models if we want. A complete example based on this documentation can be found here.

If we run the example application and go to our /items URL, we should get a response like:

[
  {
    "name": "Foo",
    "id": "item01",
    "href": "/items/item01"
  },
  {
    "name": "Bar",
    "id": "item02",
    "href": "/items/item02"
  },
  {
    "name": "Baz",
    "id": "item03",
    "href": "/items/item03"
  }
]

Limitations

Currently, query parameters will not resolve correctly. When generating a resource URL, ensure all parameters passed are path parameters, not query parameters.

This is an upstream issue, being tracked here.

Attributions

Some functionality is based on Flask-Marshmallow URLFor class.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi-hypermodel-0.2.5.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_hypermodel-0.2.5-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-hypermodel-0.2.5.tar.gz.

File metadata

  • Download URL: fastapi-hypermodel-0.2.5.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.4 CPython/3.9.5 Linux/5.8.0-1033-azure

File hashes

Hashes for fastapi-hypermodel-0.2.5.tar.gz
Algorithm Hash digest
SHA256 6613fd4cf8834717dbafe686c387a17b7ce546827f49d3d56bc6b154262f4a9f
MD5 dfd6fbf9fba1547cfb6bdb8cf9876b23
BLAKE2b-256 7d5e3f192148aa9cdc5604b17c0d38b5047f6c9fe5686ab15b239e5c4cdebbec

See more details on using hashes here.

File details

Details for the file fastapi_hypermodel-0.2.5-py3-none-any.whl.

File metadata

  • Download URL: fastapi_hypermodel-0.2.5-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.4 CPython/3.9.5 Linux/5.8.0-1033-azure

File hashes

Hashes for fastapi_hypermodel-0.2.5-py3-none-any.whl
Algorithm Hash digest
SHA256 af50e6e809523db132ec748fd5389aa2c411be7a6e93b08b2ec2529f22abaf19
MD5 bd663ec22d3f3a5143b44fdba2745fbf
BLAKE2b-256 f4cf813189a5047ced841bc2e5de44dfbced2ac1ebbff67eb33847d06e0e7ae5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page