Python / FastAPI Basics Interview Questions
How do you add GraphQL support to a FastAPI application with Strawberry?
Strawberry is a Python-first GraphQL library that uses type hints and dataclasses — a natural fit alongside FastAPI and Pydantic. It mounts a GraphQL endpoint on the FastAPI app.
# pip install strawberry-graphql[fastapi] import strawberry from strawberry.fastapi import GraphQLRouter from fastapi import FastAPI from typing import Optional # Define types with Strawberry (type hints = schema) @strawberry.type class User: id: int username: str email: str fake_users = [ User(id=1, username="alice", email="alice@example.com"), User(id=2, username="bob", email="bob@example.com"), ] # Query type @strawberry.type class Query: @strawberry.field def users(self) -> list[User]: return fake_users @strawberry.field def user(self, id: int) -> Optional[User]: return next((u for u in fake_users if u.id == id), None) # Mutation type @strawberry.type class Mutation: @strawberry.mutation def create_user(self, username: str, email: str) -> User: new_user = User(id=len(fake_users)+1, username=username, email=email) fake_users.append(new_user) return new_user schema = strawberry.Schema(query=Query, mutation=Mutation) graphql_app = GraphQLRouter(schema) app = FastAPI() app.include_router(graphql_app, prefix="/graphql") # REST routes coexist happily @app.get("/health") def health(): return {"status": "ok"}
More Related questions...