Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL query result for object that does not exist

Tags:

rest

graphql

I have a GraphQL query that calls a REST service to get the return object. The query contains an Id parameter that is then passed to the service. However, the REST service can respond with http status 404 Not Found if an object with that Id does not exist. That seems like the right response.

How do you model a Not Found response in GraphQL? Is there a way to inform the GQL caller that something does not exist?

Update
Some options I am considering:

  • Return null
  • Change the GrqlhQL Query to return a list of objects and return empty list of nothing is found
  • Return some kind of error object with an error code

but it is unclear if there is a recommended practice in GQL API design.

like image 485
Andrejs Avatar asked Mar 17 '26 06:03

Andrejs


1 Answers

You might treat it as an error and handle it accordingly.

I recommend you to check the GraphQL spec, the paragraph about error handling.
I hope it contains exactly what you are looking for.
Basically, you should return whatever you could, and inform a client about potential problems in the "errors" field.

The example from the documentation:
Request:

{
  hero(episode: $episode) {
    name
    heroFriends: friends {
      id
      name
    }
  }
}

Response:

{
  "errors": [
    {
      "message": "Name for character with ID 1002 could not be fetched.",
      "locations": [ { "line": 6, "column": 7 } ],
      "path": [ "hero", "heroFriends", 1, "name" ]
    }
  ],
  "data": {
    "hero": {
      "name": "R2-D2",
      "heroFriends": [
        {
          "id": "1000",
          "name": "Luke Skywalker"
        },
        {
          "id": "1002",
          "name": null
        },
        {
          "id": "1003",
          "name": "Leia Organa"
        }
      ]
    }
  }
}
like image 141
Daydreaming Duck Avatar answered Mar 20 '26 23:03

Daydreaming Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!