(ง •̀_•́)ง Ming's blog

Form the query you need from a GraphQL API documentation

It is my first time reading GraphQL API documentation. I don’t know if they are all this complicated so I wrote a post just in case.

You can find the API documentation and the sandbox at https://server.matters.news/playground. My goal today is to fetch all articles for a user.

When you first open the documentation (Click “DOCS” on your right-hand side), you can see a “Queries” section and a “Mutation” section. The former doesn’t require any authentication, vice versa.

parameters for user

Select the “user” option(1) under the “Queries” section. Scroll down and click the “input” option(2). This shows what parameters you need for “user”. Here you can see we need to pass userName, so the query will look something like this:

//in sandbox
query {
  user(input: { userName: "yourUserName"}) {
}

//in code
query ($userName: String!) {
  user(input: { userName: $userName }) {
  }
}

Scroll up. Under the “Type Details” section, you will find all the properties you can retrieve.

parameters for articles

Select “articles”(3) and check the arguments we need(4). We have three optional arguments: after, first, and oss.

Let’s say we want to pass in first that indicates to fetch the first N posts. The query becomes:

//in sandbox
query {
  user(input: { userName: "yourUserName"}) {
   articles(input: { first: 4 }) {
   }
  }
 }

//in code
query ($userName: String!, $first: Int!) {
  user(input: { userName: $userName }) {
      articles(input: { first: $first }) {
      }
  }
}

Moving on.

articles

Now we have selected “users(1)->articles(2)”. All articles are stored as a node under edges, so “users->articles->edges(3)->node(4)”.

Finally, we found the article node(5) and we can fill in whatever we want to fetch.

//in sandbox
 query {
  user(input: { userName: "yourUserName"}) {
   articles(input: { first: 4 }) {
    edges {
     node {
      title
      slug
      mediaHash
      createdAt
     }
    }
   }
  }
 }

//in code
query ($userName: String!, $first: Int!) {
  user(input: { userName: $userName }) {
    articles(input: { first: $first }) {
      edges {
        node {
        title
        slug
        mediaHash
        createdAt
        }
      }
    }
  }
}

This query will fetch the “title”, “slug”, “mediaHash”, and “createdAt” of the first $first articles that belongs to $userName.

#GraphQL