How to Query the Rick and Morty GraphQL API
Published:
Learn how to use a GraphQL API by querying the Rick and Morty GraphQL API with curl, the Fetch API, graphql-request, and Apollo Client.
Outline
- Introduction
- Query with GraphiQL
- Query with CURL
- Query with the Fetch API
- Query with GraphQL Request
- Query with Apollo Client
- Discover Related Articles
All of this project’s code can be found in the First Look monorepo on my GitHub.
Introduction
I’ve been going deep into GraphQL ever since I first started learning Redwood, and it’s been an interesting experiment because I started with a fully complete GraphQL project with a server and client included and integrated.
As I’ve gotten deeper into GraphQL I’ve realized this is an incredible exception to the rule, the norm is everyone creating their own bespoke combination of clients and/or servers to fit their own purposes.
Query with GraphiQL
If we wanted to take it to the total basics, you’d want to start with actually making a GraphQL query. For example, if you were to go to the following link you’ll see this:
We want to make a query, so we’ll enter the following query
for characters
, specifically their name
(the results
array is a quirk of this specific GraphQL schema).
This returns an array of names.
Watch out for Abradolf Lincler, he’s a bad dude.
Query with CURL
If you want to run this same query on the command line, you can use curl. Include the GraphQL endpoint, a header specifying that the Content-Type
is application/json
, and a data-binary
option with the query.
Query with the Fetch API
The next layer would be making a fetch
request.
Create Project
Create a new blank directory with public
and src
directories containing an index.html
and index.js
file respectively.
HTML Entrypoint
Enter the following html
boilerplate with a script
tag for index.js
.
Fetch Request
Make a fetch
request to https://rickandmortyapi.com/graphql
including:
- A
POST
request withContent-Type
ofapplication/json
- The
characters
query we wrote above asking for theirname
included in thebody
and stringified - The
results
displayed withconsole.log()
Open index.html
with a tool like Live Server.
To actually display the results of the query on the page, change the final .then
function to the following:
This doesn’t require installing dependencies, or even creating a package.json
file. However, there are many GraphQL client libraries which explore a wide range of trade offs. Use cases may include providing concise abstractions for common GraphQL functionality or adding additional features such as caching.
Query with GraphQL Request
graphql-request is a minimal GraphQL client that supports Node and browsers.
Install Dependencies
Add Scripts and Browsers List
Initialize GraphQL Request Client
Query with Apollo Client
Apollo Client is a caching GraphQL client with integrations for React and other popular frontend libraries/frameworks.