Pydantic-resolve is a schema based, hierarchical solution for data fetching and crafting.
It can compose schemas together with resolver (and dataloader), and then expose typescript types and methods to client.
It can be a super simple alternative solution for GraphQL
Features:
- with pydantic schema and instances, resolver recursively resolve uncertain nodes and their descendants.
- nodes could be modified during post-process
- plugable, easy to combine together and reuse.
User of pydantic v2, please use pydantic2-resolve instead.
pip install pydantic-resolve
build blogs with comments
import asyncio
import json
from pydantic import BaseModel
from pydantic_resolve import Resolver
class Comment(BaseModel):
id: int
content: str
class Blog(BaseModel):
id: int
title: str
content: str
comments: list[Comment] = []
def resolve_comments(self):
return get_comments(self.id)
def get_blogs():
return [
dict(id=1, title="hello world", content="hello world detail"),
dict(id=2, title="hello Mars", content="hello Mars detail"),
]
def get_comments(id):
comments = [
dict(id=1, content="world is beautiful", blog_id=1),
dict(id=2, content="Mars is beautiful", blog_id=2),
dict(id=3, content="I love Mars", blog_id=2),
]
return [c for c in comments if c['blog_id'] == id]
async def main():
blogs = [Blog.parse_obj(blog) for blog in get_blogs()]
blogs = await Resolver().resolve(blogs)
print(json.dumps(blogs, indent=2, default=lambda o: o.dict()))
asyncio.run(main())
[
{
"id": 1,
"title": "hello world",
"content": "hello world detail",
"comments": [
{
"id": 1,
"content": "world is beautiful"
}
]
},
{
"id": 2,
"title": "hello Mars",
"content": "hello Mars detail",
"comments": [
{
"id": 2,
"content": "Mars is beautiful"
},
{
"id": 3,
"content": "I love Mars"
}
]
}
]
- Quick start: https://allmonday.github.io/pydantic-resolve/about/
- API: https://allmonday.github.io/pydantic-resolve/reference_api/
- Demo: https://github.com/allmonday/pydantic-resolve-demo
- Composition oriented pattern: https://github.com/allmonday/composition-oriented-development-pattern
If this code helps and you wish to support me
Paypal: https://www.paypal.me/tangkikodo