Skip to content

Sync GraphQL server HTTP code 200/400 behavior #1320

@pylipp

Description

@pylipp

Dear team,
I have a follow-up issue to #1311.
The scenario is a sync GraphQL server with Flask, and its behavior with exceptions raised at runtime.
In our app we raise an exception from a resolver if e.g. the user does not have sufficient permission.

For the MWE I extended the example from the docs.

The behavior with Ariadne < 1.0 was a 200 response with {"data": null, "errors": [{...}]}.
With ariadne 1.0.1 it is a 400 response (same content).

I think this contradicts the GraphQL docs for HTTP 400 (copied from issue above):

Syntax or parse errors: The server couldn’t parse your request. Either the GraphQL query string is malformed, or the JSON body isn’t valid. This is the primary error status recommended by the GraphQL over HTTP specification.

My work-around is status_code = 200 if success or "data" in result else 400 to distinguish syntax/parse errors and runtime exceptions.
(Another option would be using locations: [Location!] but I'd rather not change our API).
I'm not certain if this is an ariadne bug but at least the docs should reflect this.

from ariadne import graphql_sync, make_executable_schema, QueryType
from flask import Flask, request, jsonify

app = Flask("test")

definitions = """
type Query {
    locations: [Location!]!
}
type Location {
    name: String
}
"""
query = QueryType()

class Unauthorized(Exception):
    extensions = {
        "code": "FORBIDDEN",
        "description": "You don't have permission",
    }

@query.field("locations")
def resolve_locations(*_):
    # Simulate missing permissions
    raise Unauthorized()
    return [{"name": "foo"}, {"name": "bar"}]

schema = make_executable_schema(definitions, query)

@app.post("/graphql")
def endpoint():
    success, result = graphql_sync(schema, request.get_json())
    status_code = 200 if success else 400
    return jsonify(result), status_code

app.run(host="0.0.0", port=5000, debug=True)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions