Integrate GraphQL with FastAPI
We will delve into the process of integrating GraphQL with FastAPI.
Step 1: Create virtual environment
python -m venv venv
After this, ‘venv’ folder will be created. To activate the venv environment use the command.
venv\Scripts\activate
Step 2: Install the required libraries
pip install fastapi strawberry-graphql uvicorn
Step 3: Create a file “main.py”
In this example This code sets up a FastAPI application with a simple GraphQL endpoint using the Ariadne library. It defines a GraphQL query type for a “book” with title and author fields, provides a resolver function to return static data for the “book” query, and creates a FastAPI app with a mounted GraphQL route. The server runs on `http://127.0.0.1:8000` using Uvicorn when executed.
Python3
from fastapi import FastAPI from ariadne import QueryType, gql, make_executable_schema from ariadne.asgi import GraphQL # Define a GraphQL query type query = QueryType() # Define a resolver for the "book" query @query .field( "book" ) def resolve_book( * _): return { "title" : "GraphQL Tutorial" , "author" : "GFG" } # Define the GraphQL schema using the gql function type_defs = gql( """ type Book { title: String author: String } type Query { book: Book } """ ) # Create the executable GraphQL schema schema = make_executable_schema(type_defs, query) # Create a FastAPI app app = FastAPI() # Create a GraphQL app using the Ariadne schema graphql_app = GraphQL(schema, debug = True ) # Mount the GraphQL app on the "/graphql" route app.mount( "/graphql" , graphql_app) # Run the FastAPI app if __name__ = = "__main__" : import uvicorn uvicorn.run(app, host = "127.0.0.1" , port = 8000 ) |
Step 4: Run the server
uvicorn main:app --reload
Step 5: Test Queries in GraphQL Playground:
In the GraphQL Playground, you can experiment with and test your GraphQL queries against the specified schema. For instance, you can attempt the following query. Upon clicking the run button, you should receive a response containing the user data. With this setup, Strawberry is a component of the FastAPI application, and you interact with the GraphQL endpoint via the “/graphql” FastAPI route.
Multiple Records With GraphQL
In this example below code sets up a GraphQL API using FastAPI and Strawberry. It defines two types, “User” and “Query,” with the latter providing a “users” field returning a list of User objects. The GraphQL schema is created with Strawberry, and the GraphQL app is mounted onto a FastAPI instance accessible at the “/graphql” endpoint. Users can query and retrieve a list of users with names and ages through this endpoint.
Python3
from fastapi import FastAPI from ariadne import QueryType, gql, make_executable_schema from ariadne.asgi import GraphQL # Define a GraphQL query type query = QueryType() # Define a resolver for the "books" query @query .field( "books" ) def resolve_books( * _): return [ { "title" : "Book 1" , "author" : "Author 1" }, { "title" : "Book 2" , "author" : "Author 2" }, { "title" : "Book 3" , "author" : "Author 3" }, ] # Define the GraphQL schema using the gql function type_defs = gql( """ type Book { title: String author: String } type Query { books: [Book] } """ ) # Create the executable GraphQL schema schema = make_executable_schema(type_defs, query) # Create a FastAPI app app = FastAPI() # Create a GraphQL app using the Ariadne schema graphql_app = GraphQL(schema, debug = True ) # Mount the GraphQL app on the "/graphql" route app.mount( "/graphql" , graphql_app) # Run the FastAPI app if __name__ = = "__main__" : import uvicorn uvicorn.run(app, host = "127.0.0.1" , port = 8000 ) |
Run the Server
uvicorn main:app --reload
Click on the run button, you should receive a response with all the users data:
Use of GraphQL with FastAPI
- Flexibility: One of the key advantages of using GraphQL with FastAPI is its flexibility. Clients can request only the specific data they need, minimizing unnecessary data transfer and improving overall performance.
- Type Safety: FastAPI, integrated with Strawberry, leverages Python type hints for automatic schema generation in GraphQL. This ensures that your API is type safe, reducing the likelihood of runtime errors and enhancing code reliability.
- Expressiveness: GraphQL queries are highly expressive and self-documenting, simplifying the process for developers to comprehend and interact with your API. This clarity enhances the developer experience and facilitates seamless integration.
- Efficiency: GraphQL’s efficient data fetching mechanism significantly reduces the number of requests necessary to retrieve complex data structures. This results in more streamlined and optimized data retrieval, contributing to improved efficiency in data fetching processes.
Conclusion
In conclusion, leveraging the Strawberry library to integrate GraphQL with FastAPI offers a robust solution for developing APIs that are both efficient and user-friendly. The speed of FastAPI, coupled with the flexibility of GraphQL, makes this combination an attractive choice for contemporary API development. The synergy between FastAPI and GraphQL ensures a smooth and productive development experience, whether you are constructing microservices or large-scale applications.
FastAPI – Using GraphQL
FastAPI and GraphQL have become prominent players in the realm of API development, each bringing its unique set of advantages to the table. GraphQL, initially created by Facebook, distinguishes itself with its efficiency and flexibility in data retrieval. In contrast to traditional REST APIs, GraphQL empowers clients to dictate the shape and depth of the data they need, leading to more efficient data retrieval processes.