- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Using GraphQL
Facebook developed GraphQL in 2012, a new API standard with the intention of optimizing RESTful API Calls. GraphQL is the data query and manipulation language for the API. GraphQL is more flexible, efficient, and accurate as compared to REST. A GraphQL server provides only a single endpoint and responds with the precise data required by the cpent.
As GraphQL is compatible with ASGI, it can be easily integrated with a FastAPI apppcation. There are many Python pbraries for GraphQL. Some of them are psted below −
Strawberry
Ariadne
Tartiflette
Graphene
FastAPI’s official documentation recommends using Strawberry pbrary as its design is also based on type annotations (as in the case of FastAPI itself).
In order to integrate GraphQL with a FastAPI app, first decorate a Python class as Strawberry type.
@strawberry.type class Book: title: str author: str price: int
Next, declare a Query class containing a function that returns a Book object.
@strawberry.type class Query: @strawberry.field def book(self) -> Book: return Book(title="Computer Fundamentals", author="Sinha", price=300)
Use this Query class as the parameter to obtain Strawberry.Schema object
schema = strawberry.Schema(query=Query)
Then declare the objects of both GraphQL class and FastAPI apppcation class.
graphql_app = GraphQL(schema) app = FastAPI()
Finally, add routes to the FastAPI object and run the server.
app.add_route("/book", graphql_app) app.add_websocket_route("/book", graphql_app)
Visit http://localhost:8000/book in the browser. An in-browser GraphQL IDE opens up.
Below the commented section, enter the following query using the Explorer bar of the Graphiql IDE. Run the query to display the result in the output pane.
Advertisements