Skip to content

Repository files navigation

graphql-request

Minimal GraphQL client supporting Node and browsers for scripts or simple apps

GitHub Actionnpm version

Features

  • Most simple & lightweight GraphQL client
  • Promise-based API (works with async / await)
  • Typescript support
  • Isomorphic (works with Node / browsers)

Install

npm add graphql-request graphql

Quickstart

Send a GraphQL query with a single line of code. ▶️Try it out.

import{request,gql}from'graphql-request'constquery=gql` { Movie(title: "Inception") { releaseDate actors { name } } }`request('https://api.graph.cool/simple/v1/movies',query).then((data)=>console.log(data))

Usage

import{request,GraphQLClient}from'graphql-request'// Run GraphQL queries/mutations using a static functionrequest(endpoint,query,variables).then((data)=>console.log(data))// ... or create a GraphQL client instance to send requestsconstclient=newGraphQLClient(endpoint,{headers: {}})client.request(query,variables).then((data)=>console.log(data))

Examples

Authentication via HTTP header

import{GraphQLClient,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constgraphQLClient=newGraphQLClient(endpoint,{headers: {authorization: 'Bearer MY_TOKEN',},})constquery=gql` { Movie(title: "Inception") { releaseDate actors { name } } } `constdata=awaitgraphQLClient.request(query)console.log(JSON.stringify(data,undefined,2))}main().catch((error)=>console.error(error))

TypeScript Source

Dynamically setting headers

If you want to set headers after the GraphQLClient has been initialised, you can use the setHeader() or setHeaders() functions.

import{setHeaders,setHeaderGraphQLClient}from'graphql-request'constclient=newGraphQLClient(endpoint)// Set a single headerclient.setHeader('authorization','Bearer MY_TOKEN')// Override all existing headersclient.setHeaders({authorization: 'Bearer MY_TOKEN'anotherheader: 'header_value'})

Passing more options to fetch

import{GraphQLClient,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constgraphQLClient=newGraphQLClient(endpoint,{credentials: 'include',mode: 'cors',})constquery=gql` { Movie(title: "Inception") { releaseDate actors { name } } } `constdata=awaitgraphQLClient.request(query)console.log(JSON.stringify(data,undefined,2))}main().catch((error)=>console.error(error))

TypeScript Source

Using variables

import{request,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constquery=gql` query getMovie($title: String!) { Movie(title: $title) { releaseDate actors { name } } } `constvariables={title: 'Inception',}constdata=awaitrequest(endpoint,query,variables)console.log(JSON.stringify(data,undefined,2))}main().catch((error)=>console.error(error))

TypeScript Source

Error handling

import{request,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constquery=gql` { Movie(title: "Inception") { releaseDate actors { fullname # "Cannot query field 'fullname' on type 'Actor'. Did you mean 'name'?" } } } `try{constdata=awaitrequest(endpoint,query)console.log(JSON.stringify(data,undefined,2))}catch(error){console.error(JSON.stringify(error,undefined,2))process.exit(1)}}main().catch((error)=>console.error(error))

TypeScript Source

Using require instead of import

const{ request, gql }=require('graphql-request')asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constquery=gql` { Movie(title: "Inception") { releaseDate actors { name } } } `constdata=awaitrequest(endpoint,query)console.log(JSON.stringify(data,undefined,2))}main().catch((error)=>console.error(error))

Cookie support for node

npm install fetch-cookie
require('fetch-cookie/node-fetch')(require('node-fetch'))import{GraphQLClient,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constgraphQLClient=newGraphQLClient(endpoint,{headers: {authorization: 'Bearer MY_TOKEN',},})constquery=gql` { Movie(title: "Inception") { releaseDate actors { name } } } `constdata=awaitgraphQLClient.rawRequest(query)console.log(JSON.stringify(data,undefined,2))}main().catch((error)=>console.error(error))

TypeScript Source

Receiving a raw response

The request method will return the data or errors key from the response. If you need to access the extensions key you can use the rawRequest method:

import{rawRequest,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constquery=gql` { Movie(title: "Inception") { releaseDate actors { name } } } `const{ data, errors, extensions, headers, status }=awaitrawRequest(endpoint,query)console.log(JSON.stringify({ data, errors, extensions, headers, status },undefined,2))}main().catch((error)=>console.error(error))

TypeScript Source

More examples coming soon...

FAQ

Why do I have to install graphql?

graphql-request uses a TypeScript type from the graphql package such that if you are using TypeScript to build your project and you are using graphql-request but don't have graphql installed TypeScript build will fail. Details here. If you are a JS user then you do not technically need to install graphql. However if you use an IDE that picks up TS types even for JS (like VSCode) then its still in your interest to install graphql so that you can benefit from enhanced type safety during development.

Do I need to wrap my GraphQL documents inside the gql template exported by graphql-request?

No. It is there for convenience so that you can get the tooling support like prettier formatting and IDE syntax highlighting. You can use gql from graphql-tag if you need it for some reason too.

What's the difference between graphql-request, Apollo and Relay?

graphql-request is the most minimal and simplest to use GraphQL client. It's perfect for small scripts or simple apps.

Compared to GraphQL clients like Apollo or Relay, graphql-request doesn't have a built-in cache and has no integrations for frontend frameworks. The goal is to keep the package and API as minimal as possible.

About

Minimal GraphQL client supporting Node and browsers for scripts or simple apps

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages