How to respond with different status codes in GraphQL?
How to respond with different status codes in GraphQL?
Responding with different status codes in GraphQL can be a bit nuanced compared to traditional REST APIs. Here’s a comprehensive answer to the interview question "How to respond with different status codes in GraphQL?":
GraphQL typically returns a 200 OK status code for all responses, even if there are errors within the response. This is because GraphQL is designed to handle errors within the response body itself, rather than relying solely on HTTP status codes. The response will include a data field for successful parts of the query and an errors field for any issues encountered during execution
While the default behavior is to return 200 OK, it is possible to customize HTTP status codes in GraphQL, though this requires additional implementation at the server level. Here are some methods and best practices:
GraphQLite allows you to throw exceptions that can set specific HTTP status codes. For example, you can throw a GraphQLException with a custom status code:
use TheCodingMachine\GraphQLite\Exceptions\GraphQLException;
throw new GraphQLException("Not found", 404);
This will generate a response with a 404 Not Found status code
Apollo Server provides a way to set HTTP status codes by throwing errors with specific extensions. For example:
import { GraphQLError } from 'graphql';
const resolvers = {
Query: {
someField() {
throw new GraphQLError('the error message', {
extensions: {
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.