Fastapi使用GraphQL

from fastapi import FastAPI, Request
import strawberry
from strawberry.asgi import GraphQL
from strawberry.fastapi import GraphQLRouter
from pydantic import BaseModel, Field
from typing import List, Optional, Union

app = FastAPI()


@strawberry.type
class User(BaseModel):
    name: str
    age: int


@strawberry.type
class Student:
    name: str
    age: int


@strawberry.type
class Teacher:
    id: int
    name: str
    age: int
    students: List[Student]


teachers = [
    {
        'id': 1,
        'name': 'gao',
        'age': 30,
        'students': [Student(name='aaa', age=10), Student(name='bbb', age=10)]
    },
    {
        'id': 2,
        'name': 'feng',
        'age': 20,
        'students': [Student(name='ccc', age=10), Student(name='ddd', age=10)]
    }
]


@strawberry.type
class Query:
    @strawberry.field
    def user1(self) -> User:
        return User(name="Patrick", age=100)

    @strawberry.field
    def teacher(self, id: Optional[int] = None, id_gt1: Optional[int] = None) -> List[Teacher]:
        if id:
            return [Teacher(**(teachers[0]))]
        return [Teacher(**t) for t in teachers]


schema = strawberry.Schema(query=Query)


async def get_context(request: Request):
    print(request.base_url)
    print(request.url)
    print(request.scope.get('path'))


graphql_app = GraphQLRouter(schema, context_getter=get_context)
app.include_router(graphql_app, prefix="/graphql")



if __name__ == '__main__':
    import uvicorn
    DEBUG = True
    HOST = "127.0.0.1"
    PORT = 9000
    WORKERS = 1
    uvicorn.run('main:app', host=HOST, port=PORT,
                reload=DEBUG)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python fastapi is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. Fastapi provides a built-in support for GraphQL via the `graphene` library. GraphQL is a query language for APIs that provides a more efficient, powerful and flexible alternative to REST. With GraphQL, clients can specify exactly what they need, and they get only that information back. This reduces over-fetching and under-fetching of data, makes APIs faster and more efficient, and helps developers build better user interfaces. To use Fastapi with GraphQL, you need to install `graphene` library and import it into your Fastapi application. Here's a simple example: ```python from fastapi import FastAPI from graphene import ObjectType, String, Schema app = FastAPI() class Query(ObjectType): hello = String(name=String(default_value="World")) def resolve_hello(root, info, name): return f'Hello {name}!' schema = Schema(query=Query) @app.post("/graphql") async def graphql(query: str): result = schema.execute(query) return result.data ``` In this example, we define a `Query` class that extends `graphene.ObjectType` and contains a single field called `hello`. The `hello` field takes an argument `name` with a default value of "World". When the `hello` field is resolved, it returns a string that says "Hello {name}!". We then create a `Schema` object, passing in our `Query` class as the `query` argument. Finally, we define a Fastapi route that accepts a `POST` request with a GraphQL query as the `query` parameter. We execute the query using the `schema.execute()` method and return the `result.data` as the response. This is just a simple example, but Fastapi with GraphQL provides a powerful platform for building APIs that are flexible, efficient and easy to use.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值