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

{
  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:

{
  site {
    siteMetadata {
      title
    }
  }
}

And GraphQL editor should return response:

{
  "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:

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"

query BlogPost {
  markdownRemark(frontmatter: {
    slug: {
      eq: "/greetings-post"
    }
  }) {
    html
    frontmatter {
      title
      date
    }
  }
}
Share:

About

My name is Max, also known as @mxkvl.

I am a software developer, currently working mostly with TypeScript, React and Node ecosystems.

I write a blog about topics that interest me most: programming languages in general, TypeScript, testing, writing and other great stuff.

Join the Mailing List