Example for Lists
In the below example, create a GraphQL schema to define a list of users.
Step 1: Define the Schema
Let’s create a schema and save the file as schema.graphql.
type Query {
users: [User]! #Non-Null List - User
}
type User {
userID: ID! #Non-Null field - userID
userName: String
userEmail: String
}
Step 2: Implement Resolvers
Let’s set up the server, save the file as server.js and we will implement resolvers for the users list.
Javascript
const express = require( 'express' ); const { graphqlHTTP } = require( 'express-graphql' ); const { buildSchema } = require( 'graphql' ); const fs = require( 'fs' ); const path = require( 'path' ); const schema = buildSchema(fs.readFileSync(path.join(__dirname, 'schema.graphql' ), 'utf8' )); const users = [ { userID: '1001' , userName: 'User1' , userEmail: 'user1@gmail.com' }, { userID: '1002' , userName: 'User2' , userEmail: 'user2@gmail.com' }, ]; const root = { users: () => users, }; const app = express(); app.use( '/graphql' , graphqlHTTP({ schema: schema, rootValue: root, graphiql: true , }) ); const PORT = process.env.PORT || 4000; app.listen(PORT, () => { console.log(`GraphQL server is running on http: //localhost:${PORT}/graphql`); }); |
Step 3: Test Your List in GraphiQL
Run your GraphQL server.
node server.js
Output:
Step 4: Execute the Below Query in the GraphiQL Interface
{
users {
userID
userName
userEmail
}
}
Output:
We will receive a response with the list of users
Lists and Non-Null in GraphQL Schema
GraphQL is a powerful open-source Query Language for APIs. In 2012 it was first developed by a team of developers in Facebook and then it was later made public to the general people by making it open-source. Now it is being maintained by the GraphQL community.
GraphQL is most commonly known for its single endpoint query which allows the user to define a single endpoint to fetch all the information needed. The benefit of using single endpoint queries is that they help the user in reducing fetching too much data or less amount of data than required.