Python / FastAPI 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"}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
