{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# FastAPI 之 GraphQL\n", "\n", "参考:[GraphQL](https://fastapi.tiangolo.com/zh/advanced/graphql/)\n", "\n", "因为 FastAPI 是基于 ASGI 标准的,所以集成任何与 ASGI 兼容的 GraphQL 库都非常容易。\n", "\n", "在同一个应用程序中,可以将普通的 FastAPI 路径操作与 GraphQL 结合使用。\n", "\n", "```{tip}\n", "- GraphQL解决了一些非常具体的用例。\n", "- 与普通 web API 相比,它有优点也有缺点。\n", "- 确保您评估了用例的好处是否弥补了缺点。🤓\n", "```\n", "\n", "# FastAPI:GraphQL + Strawberry\n", "\n", "如果你需要或者想要使用 GraphQL, [Strawberry](https://strawberry.rocks/) 是推荐的库,因为它的设计最接近 FastAPI 的设计,它都是基于类型注释的。\n", "\n", "下面是关于如何将 Strawberry 与 FastAPI 集成的小样例:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import strawberry\n", "from fastapi import FastAPI\n", "from strawberry.asgi import GraphQL\n", "\n", "\n", "@strawberry.type\n", "class User:\n", " name: str\n", " age: int\n", "\n", "\n", "@strawberry.type\n", "class Query:\n", " @strawberry.field\n", " def user(self) -> User:\n", " return User(name=\"Patrick\", age=100)\n", "\n", "\n", "schema = strawberry.Schema(query=Query)\n", "\n", "\n", "graphql_app = GraphQL(schema)\n", "\n", "app = FastAPI()\n", "app.add_route(\"/graphql\", graphql_app)\n", "app.add_websocket_route(\"/graphql\", graphql_app)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "更多样例可以参考:[strawberry-fastapi](https://strawberry.rocks/docs/integrations/fastapi)。" ] } ], "metadata": { "kernelspec": { "display_name": "py310", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.6" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "7e468feb35f514aafce3cc952fb1f3b43bab876fc14f6450ea05924ae7e4a934" } } }, "nbformat": 4, "nbformat_minor": 2 }