How to Implement Error Handling with Specific Status Codes in FastAPI GraphQL API

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật