Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL to query something other than ID

I am using Strapi with Nuxt.js to implement my first Headless CMS. I am using Apollo and GraphQL.

I am running into the current error and I've had no luck to figure this out for days.

If I write:

query Page($id: ID!) {
  page(id: $id) {
    id
    slug
    title
  }
}

And pass the following variable:

{
  "id" : "1"
}

I received the correct expected result:

{
  "data": {
    "page": {
      "id": "1",
      "slug": "/",
      "title": "Homepage"
    }
  }
}

HOWEVER, I would like to get the content not via ID, but via a field that I created in Strapi, called "slug". Looking around, it seems like I should be able to do something like:

query Page($slug: String!) {
  page(slug: $slug) {
    id
    slug
    title
  }
}

With variable:

{
  "slug" : "/"
}

but I receive this error:

{
  "error": {
    "errors": [
      {
        "message": "Unknown argument \"slug\" on field \"page\" of type \"Query\".",
        "locations": [
          {
            "line": 2,
            "column": 8
          }
        ],
        "extensions": {
          "code": "GRAPHQL_VALIDATION_FAILED",
          "exception": {
            "stacktrace": [

... the error continues....

[UPDATE] After Italo replied, I changed it into:

query Pages($slug: String!) {
  page(where: {slug: $slug}) {
    id
    slug
    title
  }
}

But I now get the following error:

{
  "error": {
    "errors": [
      {
        "message": "Unknown argument \"where\" on field \"page\" of type \"Query\".",

I also noticed that I get a query if I change "page" into "pages", but it shows all of the pages...

What am I missing? Thanks!

like image 829
Saro Avatar asked Feb 03 '23 16:02

Saro


1 Answers

To query one item using something other than the primary key (and using just the default built-in queries from Strapi), you need to use the filters avaiable as a where clause:

query Pages($slug: String!) {
  pages(where: {slug: $slug}) {
    id
    slug
    title
  }
}
  • Notice I'm using the endpoint Pages instead of Page, so this will return an array.
  • Check the filters section here: https://strapi.io/documentation/3.0.0-alpha.x/guides/graphql.html#configurations

Tip: use the Graphql interface avaiable in http://localhost:1337/graphql to test that. (if you are not already)

like image 147
Italo Ayres Avatar answered Feb 20 '23 09:02

Italo Ayres