Table of Contents
What is GraphQL?
What are we building
start
GraphQL schema type
GraphQL parser
Query
Mutations
Summarize
Home Web Front-end CSS Tutorial Get Started Building GraphQL APIs With Node

Get Started Building GraphQL APIs With Node

Apr 09, 2025 am 09:14 AM

Get Started Building GraphQL APIs With Node

We all have many interests and hobbies. For example, I'm interested in JavaScript, '90s indie rock and hip-hop, unpopular jazz, the city of Pittsburgh, pizza, coffee, and movies starring John Lury. Our family, friends, acquaintances, classmates and colleagues also have their own social relationships, interests and hobbies. Some of these relationships and interests overlap, like my friend Riley is just as interested in 90s hip-hop and pizza as I do. Others have no overlap, such as my colleague Harrison, who prefers Python over JavaScript, drinks only tea and prefers current pop music. All in all, each of us has a map of connection with people in our lives and how our relationships and interests overlap.

This type of interrelated data is exactly the challenge GraphQL initially started to solve in API development. By writing the GraphQL API, we are able to effectively connect data, reducing complexity and request count while allowing us to provide the required data to the client accurately. (If you prefer the GraphQL metaphor, check out Meet GraphQL at a cocktail party.)

In this article, we will use the Apollo Server package to build a GraphQL API in Node.js. To do this, we will explore the basic GraphQL topic, write GraphQL patterns, develop code to parse our pattern functions, and access our API using the GraphQL Playground user interface.

What is GraphQL?

GraphQL is an open source query and data manipulation language for APIs. Its development goal is to provide a single endpoint for data, allowing applications to request the exact data they need. This not only helps simplify our UI code, but also improves performance by limiting the amount of data that needs to be sent over the network.

What are we building

To follow this tutorial, you need Node v8.x or later and some experience using the command line.

We will build an API application for book excerpts that allow us to store memorable paragraphs from what we read. API users will be able to perform "CRUD" (create, read, update, delete) operations on their excerpts:

  • Create a new excerpt
  • Read a single excerpt and a list of excerpts
  • Updated excerpts
  • Delete the excerpt

start

First, create a new directory for our project, initialize a new node project, and install the dependencies we need:

 <code># 创建新目录mkdir highlights-api # 进入目录cd highlights-api # 初始化新的节点项目npm init -y # 安装项目依赖项npm install apollo-server graphql # 安装开发依赖项npm install nodemon --save-dev</code>
Copy after login

Before we proceed, let's break down our dependencies:

  • apollo-server is a library that allows us to use GraphQL in our Node applications. We will use this as a standalone library, but the Apollo team has also created middleware for working with Express, hapi, Fastify, and Koa in existing Node web applications.
  • graphql contains the GraphQL language and is a required peer dependency for apollo-server .
  • nodemon is a useful library that will monitor our project for changes and automatically restart our server.

After installing our package, let's create the root file of the application, named index.js . Now, we will use console.log() to output a message in this file:

 <code>console.log("? Hello Highlights");</code>
Copy after login

To simplify our development process, we will update scripts object in the package.json file to use nodemon package:

 <code>"scripts": { "start": "nodemon index.js" },</code>
Copy after login

Now we can start our application by typing npm start in the terminal application. If everything works fine, will you see ? Hello Highlights logged to your terminal.

GraphQL schema type

Patterns are written representations of our data and interactions. Through the Required Pattern, GraphQL implements strict planning for our API. This is because the API can only return data defined in the schema and perform interactions. The basic component of the GraphQL pattern is the object type. GraphQL contains five built-in types:

  • String: strings encoded using UTF-8 characters
  • Boolean: True or false value
  • Int: 32-bit integer
  • Float: Float value
  • ID: Unique identifier

We can use these basic components to build patterns for APIs. In a file called schema.js , we can import the gql library and prepare the file for our schema syntax:

 <code>const { gql } = require('apollo-server'); const typeDefs = gql` # 模式将放在这里`; module.exports = typeDefs;</code>
Copy after login

To write our pattern, we first define the type. Let's consider how we define patterns for our excerpt application. First, we will create a new type called Highlight :

 <code>const typeDefs = gql` type Highlight { } `;</code>
Copy after login

Each excerpt will have a unique ID, some content, title, and author. The Highlight mode will look like this:

 <code>const typeDefs = gql` type Highlight {  id: ID  content: String  title: String  author: String } `;</code>
Copy after login

We can make some of these fields a required field by adding an exclamation mark:

 <code>const typeDefs = gql` type Highlight {  id: ID!  content: String!  title: String  author: String } `;</code>
Copy after login

Although we have defined an object type for our excerpt, we also need to describe how the client gets that data. This is called a query. We'll dive into the query later, but now let's describe how someone retrieves excerpts in our pattern. When all of our excerpts are requested, the data will be returned as an array (denoted as [Highlight] ), and when we want to retrieve a single excerpt we need to pass the ID as a parameter.

 <code>const typeDefs = gql` type Highlight {  id: ID!  content: String!  title: String  author: String } type Query {  highlights: [Highlight]!  highlight(id: ID!): Highlight } `;</code>
Copy after login

Now, in the index.js file, we can import our type definition and set up Apollo Server:

 <code>const {ApolloServer } = require('apollo-server'); const typeDefs = require('./schema'); const server = new ApolloServer({ typeDefs }); server.listen().then(({ url }) => { console.log(`? Highlights server ready at ${url}`); });</code>
Copy after login

If we keep the node process running, the application will be updated and restarted automatically, but if not, typing npm start from the project's directory in the terminal window will start the server. If we look at the terminal, we should see that nodemon is monitoring our files and the server is running on the local port:

 <code>[nodemon] 2.0.2 [nodemon] to restart at any time, enter `rs` [nodemon] watching dir(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node index.js` ? Highlights server ready at http://localhost:4000/</code>
Copy after login

Accessing the URL in a browser launches the GraphQL Playground application, which provides a user interface for interacting with our API.

GraphQL parser

Although we have developed our project using initial mode and Apollo Server settings, we are not able to interact with our API yet. To do this, we will introduce the parser. The parsers perform the exact operations implied by their name; they parse data requested by the API user. We will write these parsers by first defining them in our schema and then implementing logic in our JavaScript code. Our API will contain two types of parsers: query and mutation.

Let's first add some data to interact with. In an application, this is usually the data we retrieve and write from the database, but for our example, let's use an array of objects. Add the following to the index.js file:

 let highlights = [
  {
    id: '1',
    content: 'One day I will find the right words, and they will be simple.',
    title: 'Dharma Bums',
    author: 'Jack Kerouac'
  },
  {
    id: '2',
    content: 'In the limits of a situation there is humor, there is grace, and everything else.',
    title: 'Arbitrary Stupid Goal',
    author: 'Tamara Shopsin'
  }
]
Copy after login

Query

Query requests specific data from the API and displays it in its desired format. The query will then return an object containing the data requested by the API user. A query never modifies data; it only accesses data. We have written two queries in the schema. The first returns an array of excerpts, and the second returns a specific excerpt. The next step is to write a parser that will return the data.

In the index.js file, we can add a resolvers object that can contain our query:

 const resolvers = {
  Query: {
    highlights: () => highlights,
    highlight: (parent, args) => {
      return highlights.find(highlight => highlight.id === args.id);
    }
  }
};
Copy after login

highlights query returns a complete array of excerpt data. highlight query accepts two parameters: parent and args . parent is the first parameter to any GraqhQL query in Apollo Server and provides a way to access the query context. The args parameter allows us to access user-provided parameters. In this case, the API user will provide id parameter to access a specific excerpt.

We can then update our Apollo Server configuration to include the resolver:

 const server = new ApolloServer({ typeDefs, resolvers });
Copy after login

After writing our query parser and updating Apollo Server, we can now use the GraphQL Playground query API. To access GraphQL Playground, visit http://localhost:4000 in your web browser.

The query format is as follows:

 query {
  queryName {
      field
      field
    }
}
Copy after login

With this in mind, we can write a query that requests the ID, content, title, and author of each of our excerpts:

 query {
  highlights {
    id
    content
    title
    author
  }
}
Copy after login

Suppose we have a page in the UI that lists only the title and author of our highlighted text. We don't need to retrieve the content of each excerpt. Instead, we can write a query that only requests the data we need:

 query {
  highlights {
    title
    author
  }
}
Copy after login

We also wrote a parser that querys individual comments by including ID parameters in our query. We can do this:

 query {
  highlight(id: "1") {
    content
  }
}
Copy after login

Mutations

When we want to modify data in the API, we use mutations. In our excerpt example, we will want to write a variant to create a new excerpt, an updated existing excerpt, and a third to delete excerpt. Similar to a query, mutations should also return results in the form of objects, usually the final result of the operation performed.

The first step in updating anything in GraphQL is writing patterns. We can include variants in the schema by adding a variant type to our schema.js file:

 type Mutation {
  newHighlight (content: String! title: String author: String): Highlight!
  updateHighlight(id: ID! content: String!): Highlight!
  deleteHighlight(id: ID!): Highlight!
}
Copy after login

Our newHighlight variant will take the required value of content and optional title and author values ​​and return a Highlight . updateHighlight variant will require highlight id and content to be passed as parameter values ​​and will return the updated Highlight . Finally, the deleteHighlight variant will accept an ID parameter and will return the deleted Highlight .

After updating the pattern to include mutations, we can now update resolvers in the index.js file to perform these operations. Each mutation updates our highlights data array.

 const resolvers = {
  Query: {
    highlights: () => highlights,
    highlight: (parent, args) => {
      return highlights.find(highlight => highlight.id === args.id);
    }
  },
  Mutation: {
    newHighlight: (parent, args) => {
      const highlight = {
        id: String(highlights.length 1),
        title: args.title || '',
        author: args.author || '',
        content: args.content
      };
      highlights.push(highlight);
      return highlight;
    },
    updateHighlight: (parent, args) => {
      const index = highlights.findIndex(highlight => highlight.id === args.id);
      const highlight = {
        id: args.id,
        content: args.content,
        author: highlights[index].author,
        title: highlights[index].title
      };
      highlights[index] = highlight;
      return highlight;
    },
    deleteHighlight: (parent, args) => {
      const deletedHighlight = highlights.find(
        highlight => highlight.id === args.id
      );
      highlights = highlights.filter(highlight => highlight.id !== args.id);
      return deletedHighlight;
    }
  }
};
Copy after login

After writing these mutations, we can practice mutation data using GraphQL Playground. The structure of the mutation is almost the same as the query, specifying the name of the mutation, passing parameter values, and requesting the return of specific data. Let's first add a new excerpt:

 mutation {
  newHighlight(author: "Adam Scott" title: "JS Everywhere" content: "GraphQL is awesome") {
    id
    author
    title
    content
  }
}
Copy after login

We can then write a mutation to update the excerpt:

 mutation {
  updateHighlight(id: "3" content: "GraphQL is rad") {
    id
    content
  }
}
Copy after login

And delete excerpts:

 mutation {
  deleteHighlight(id: "3") {
    id
  }
}
Copy after login

Summarize

Congratulations! You have now successfully built a GraphQL API that uses Apollo Server and can run GraphQL queries and mutations on in-memory data objects. We have laid a solid foundation for exploring the world of GraphQL API development.

Here are some next steps to improve your level:

  • Learn about nested GraphQL queries and mutations.
  • Follow the Apollo full stack tutorial.
  • Update the example to include a database such as MongoDB or PostgreSQL.
  • Explore more excellent CSS-Tricks GraphQL articles.
  • Use your newly acquired GraphQL knowledge to build static websites using Gatsby.

The above is the detailed content of Get Started Building GraphQL APIs With Node. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Creating Your Own Bragdoc With Eleventy Creating Your Own Bragdoc With Eleventy Mar 18, 2025 am 11:23 AM

No matter what stage you’re at as a developer, the tasks we complete—whether big or small—make a huge impact in our personal and professional growth.

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

See all articles