Home > database >  How to execute a GraphQL query from a Next.js app?
How to execute a GraphQL query from a Next.js app?

Time:12-01

I have this Insomnia GraphQL command that I'm trying to put into a Next.js app. This is the actual API call that I've been running in Insomnia that I plan on moving into my Next.js app.

query getCharacters {
  characters(page: 1) {
    info {
      count
    }
    results {
      id
      name
    }
  }
}

It's a super simple function... Here's what it looks like in Insomnia:
query in graphiql

I found this example code for doing GraphQL function calls with Next.js: https://github.com/vercel/next.js/blob/canary/examples/api-routes-graphql. It requires typeDefs and resolvers to create a schema. I'm unfamiliar with this type of function call as I have always used simple rest APIs for previous apps.

I don't know what the typeDefs and resolvers are for https://rickandmortyapi.com/graphql 's getCharacters function?

Maybe I'm going about this incorrectly and I don't actually need to get getCharacter's typeDefs and resolvers. If I'm approaching this incorrectly, can someone show me how to execute this getCharacters function in a next.js graphql function properly?

CodePudding user response:

Your app is going to act as a GraphQL client. TypeDefs and resolvers are written on the server. For example https://rickandmortyapi.com/graphql is the GraphQL server that you are trying to connect to and getCharacters is a particular query on that server.

There are many ways to execute a GraphQL query from next.js - these are well described in this article. I recommend using the apollo-client method rather than the lower level fetch or axios.

  • Related