Basic example of GraphQL in GatsbyJS

GraphQL editor is available in your local GatsbyJS app on http://localhost:8000/__graphql

In the editor you can write a query and you will get information from API’s that based on this written query

Example

1
2
3
4
5
{
  site {
    
  }
}

site is like an object/schema that contains some information about your website. For example, it contains information about siteMetadata (that you configured in gatsby-config.js file)

sideMetadata is an object and has three fields title, description, author.

So, if you wanna get information about siteMetadata (specifically - title) from API you should write query like this:

1
2
3
4
5
6
7
{
  site {
    siteMetadata {
      title
    }
  }
}

And GraphQL editor should return response:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
  "data": {
    "site": {
      "siteMetadata": {
        "title": "Gatsby Blog Sample"
      }
    }
  },
  "extensions": {}
}

You can find the same code example in default component Layout of generated (by GatsbyJS > Gatsby CLI) app:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const Layout = ({ children }: { children: React.ReactNode }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)
  // ...

Query with parameters

There is parameter frontmatter that includes slug

This query should return data of the post that has slug = “/greetings-post”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
query BlogPost {
  markdownRemark(frontmatter: {
    slug: {
      eq: "/greetings-post"
    }
  }) {
    html
    frontmatter {
      title
      date
    }
  }
}