Hyperlinks for pydantic models
Project description
Read a blog post from the library author discussing why this library exists.
In a typical web application relationships between resources are modeled by primary and foreign keys in a database (integers, UUIDs, etc.). The most natural way to represent relationships in REST APIs is by URLs to the related resources (explained in this blog).
hrefs makes it easy to add hyperlinks between pydantic models in a declarative way. Just declare a Href field and the library will automatically convert between keys and URLs:
from hrefs import Href, BaseReferrableModel
from pydantic import BaseModel
class Book(BaseReferrableModel):
id: int
class Config:
details_view = "get_book"
class Library(BaseModel):
books: list[Href[Book]]
@app.get("/books/{id}")
def get_book(id: int) -> Book:
return Book(id=id)
@app.get("/library")
def get_library() -> Library:
"""
Will serialize into:
{"books":["https://example.com/books/1","https://example.com/books/2","https://example.com/books/3"]}
"""
return Library(books=[1,2,3])
@app.post("/library")
def post_library(library: Library):
"""
Assuming the request contains
{"books":["https://example.com/books/1","https://example.com/books/2","https://example.com/books/3"]}
Will deserialize into: [1,2,3]
"""
write_to_database([href.key for href in library.books])
hrefs was written especially with FastAPI in mind, but integrates into any application or framework using pydantic to parse and serialize models.
Check out the documentation to get started!
Installation
Install the library using pip or your favorite package management tool:
$ pip install hrefs
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file hrefs-0.13.tar.gz
.
File metadata
- Download URL: hrefs-0.13.tar.gz
- Upload date:
- Size: 42.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.28.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9d93125db704e382d3fc42eca7ade97b7322260feddea8f660534a503b835525 |
|
MD5 | 71cfc2348a3f3fa44442846da83ff994 |
|
BLAKE2b-256 | 66c46b9b951d25ff4bb8e537b26c00c68b4d078e1726901f9dc79148eedf24ae |
File details
Details for the file hrefs-0.13-py3-none-any.whl
.
File metadata
- Download URL: hrefs-0.13-py3-none-any.whl
- Upload date:
- Size: 16.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.28.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d5f00c835c7d6231324ec07a06f1f96da192b914b63bb0e72cc67c6f1684b495 |
|
MD5 | dfd086bfddfe487d29fa5a36d9a761b7 |
|
BLAKE2b-256 | 9c6eb95d80d57316254026af9641fa830726be55a88297b0b22cf429d6451995 |