FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts. It uses Python type hints to validate, serialize, and deserialize data. For example, when defining a route, you can specify the input and output data types clearly.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
In this code, the item_id
parameter is expected to be an integer. FastAPI will automatically validate the input and return an error if the input is not a valid integer.
GraphQL is centered around the concept of a schema. A schema defines the types of data that can be queried and the operations (queries and mutations) that can be performed on them. For example, a simple schema for a blog post might look like this:
type BlogPost {
id: ID!
title: String!
content: String!
}
type Query {
getBlogPost(id: ID!): BlogPost
}
Here, BlogPost
is a custom type, and Query
is the root type for read - only operations. The getBlogPost
query takes an id
as a parameter and returns a BlogPost
object.
To integrate GraphQL with FastAPI, we can use the graphene
library, which is a Python library for building GraphQL schemas.
from fastapi import FastAPI
from graphene import ObjectType, String, Schema
from starlette_graphene3 import GraphQLApp, make_graphiql_handler
app = FastAPI()
class Query(ObjectType):
hello = String()
def resolve_hello(self, info):
return "Hello, world!"
schema = Schema(query=Query)
app.add_route("/graphql", GraphQLApp(schema, on_get=make_graphiql_handler()))
In this code, we first define a simple GraphQL schema with a single query hello
. Then we integrate it with FastAPI using starlette_graphene3
. The GraphiQL
interface is also enabled for easy testing of the GraphQL API.
User
type with a lot of fields related to addresses, you can create a separate Address
type and reference it in the User
type.type Address {
street: String!
city: String!
country: String!
}
type User {
id: ID!
name: String!
address: Address
}
In FastAPI, you can use the built - in exception handlers to handle errors. For example:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id < 0:
raise HTTPException(status_code=400, detail="Item ID cannot be negative")
return {"item_id": item_id}
In GraphQL, errors are typically returned in the errors
field of the response. You can also use custom error types in your schema to provide more detailed error information.
Combining FastAPI and GraphQL offers a powerful way to create flexible and efficient APIs. FastAPI provides a fast and easy - to - use web framework with built - in data validation and serialization, while GraphQL allows clients to have fine - grained control over the data they receive. By following the common and best practices outlined in this blog, developers can build high - performance, secure, and maintainable APIs.