search
HomeWeb Front-endCSS TutorialGet Started Building GraphQL APIs With Node

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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'
  }
]

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);
    }
  }
};

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 });

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
    }
}

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
  }
}

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
  }
}

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
  }
}

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!
}

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;
    }
  }
};

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
  }
}

We can then write a mutation to update the excerpt:

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

And delete excerpts:

 mutation {
  deleteHighlight(id: "3") {
    id
  }
}

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
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
A Little Reminder That Pseudo Elements are Children, Kinda.A Little Reminder That Pseudo Elements are Children, Kinda.Apr 19, 2025 am 11:39 AM

Here's a container with some child elements:

Menus with 'Dynamic Hit Areas'Menus with 'Dynamic Hit Areas'Apr 19, 2025 am 11:37 AM

Flyout menus! The second you need to implement a menu that uses a hover event to display more menu items, you're in tricky territory. For one, they should

Improving Video Accessibility with WebVTTImproving Video Accessibility with WebVTTApr 19, 2025 am 11:27 AM

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."- Tim Berners-Lee

Weekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteWeekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteApr 19, 2025 am 11:25 AM

In this week's roundup: datepickers are giving keyboard users headaches, a new web component compiler that helps fight FOUC, we finally get our hands on styling list item markers, and four steps to getting webmentions on your site.

Making width and flexible items play nice togetherMaking width and flexible items play nice togetherApr 19, 2025 am 11:23 AM

The short answer: flex-shrink and flex-basis are probably what you’re lookin’ for.

Position Sticky and Table HeadersPosition Sticky and Table HeadersApr 19, 2025 am 11:21 AM

You can't position: sticky; a

Weekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryWeekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryApr 19, 2025 am 11:18 AM

In this week's look around the world of web platform news, Google Search Console makes it easier to view crawled markup, we learn that custom properties

IndieWeb and WebmentionsIndieWeb and WebmentionsApr 19, 2025 am 11:16 AM

The IndieWeb is a thing! They've got a conference coming up and everything. The New Yorker is even writing about it:

See all articles

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.