How can I handle errors with status codes (404, 422, 500, 401, and 403) in a GraphQL API using FastAPI and Strawberry?
I’m developing a GraphQL API using FastAPI and Strawberry, and I need to implement robust error handling that returns appropriate HTTP status codes based on different error scenarios. Specifically, I want to handle the following status codes:
404 Not Found: For resources that cannot be found.
422 Unprocessable Entity: For validation errors when input data is incorrect.
500 Internal Server Error: For unexpected server errors.
401 Unauthorized: For requests that require authentication but are not authenticated.
403 Forbidden: For requests that are authenticated but do not have permission to access the resource.
Any guidance on implementing this effectively within a GraphQL context using Strawberry would be highly appreciated!
Thank you!
HTTP status codes are typically used for REST APIs, which are based on HTTP protocols. In the case of GraphQL, which is transport agnostic, using HTTP status codes for errors doesn’t always make sense. For more details on this, you can refer to this answer.
Regarding your specific question about Strawberry and FastAPI, instead of relying on HTTP status codes, you can return proper error responses within the GraphQL specification. The extensions
attribute in GraphQL allows you to include custom error codes in the response object.
Please refer this answer.
Here’s a sample GraphQL implementation using Strawberry:
import strawberry
from graphql import GraphQLError
from typing import Optional
@strawberry.type
class Dummy:
id: Optional[str] = None
@strawberry.type
class Query:
@strawberry.field
async def dummyQuery(self, info, id: strawberry.ID) -> Optional[Dummy]:
if id == 'Error':
raise GraphQLError(
"Authorization failed",
extensions={"error_code": "405"}
)
return Dummy(id="Valid response")
Now, if you make the following GraphQL request in GraphiQL, which includes two queries:
{
firstQuery: dummyQuery(id: "hello") {
... on Dummy {
id
}
}
secondQuery: dummyQuery(id: "Error") {
... on Dummy {
id
}
}
}
You will get this response, where one query returns an error object while the other returns a proper response:
{
"data": {
"firstQuery": {
"id": "Valid response"
},
"secondQuery": null
},
"errors": [
{
"message": "Authorization failed",
"locations": [
{
"line": 7,
"column": 3
}
],
"path": [
"secondQuery"
],
"extensions": {
"error_code": "405"
}
}
]
}
This approach follows GraphQL standards. However, if you absolutely need to return a specific HTTP status code, you can achieve this by modifying the response
object within the resolver using info.context
:
@strawberry.type
class Query:
@strawberry.field
async def dummyQuery(self, info, id: ID) -> Optional[Dummy]:
if id == 'Error':
info.context["response"].status_code = 403
raise GraphQLError("Authorization failed", extensions={"error_code": "405"})
return Dummy(id="Valid response")
This allows you to set a custom HTTP status code (e.g., 403) alongside the GraphQL error response.
0