Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jasujm/hrefs
Hyperlinks for pydantic models
https://github.com/jasujm/hrefs
api fastapi hrefs pydantic python rest starlette
Last synced: 10 days ago
JSON representation
Hyperlinks for pydantic models
- Host: GitHub
- URL: https://github.com/jasujm/hrefs
- Owner: jasujm
- License: mit
- Created: 2021-11-20T15:42:16.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2023-12-05T20:30:04.000Z (12 months ago)
- Last Synced: 2024-11-06T00:15:46.031Z (10 days ago)
- Topics: api, fastapi, hrefs, pydantic, python, rest, starlette
- Language: Python
- Homepage: https://hrefs.readthedocs.io/
- Size: 205 KB
- Stars: 16
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.rst
- Changelog: CHANGELOG.rst
- Contributing: CONTRIBUTING.rst
- License: LICENSE
Awesome Lists containing this project
README
Hyperlinks for pydantic models
==============================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:.. code-block:: python
from hrefs import Href, BaseReferrableModel
from pydantic import BaseModelclass Book(BaseReferrableModel):
id: intclass 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:
.. code-block:: console
$ pip install hrefs