Basic Types
In most situations, the first step is to specify the types for your API. You can do that with code-first constructors, or with the GraphQL schema language passed to the buildSchema function.
The GraphQL schema language supports the scalar types of String, Int, Float, Boolean, and ID, so you can use these directly in SDL schemas.
By default, every type is nullable - it’s legitimate to return null as any of the scalar types. Use an exclamation point to indicate a type cannot be nullable, so String! is a non-nullable string.
To use a list type, surround the type in square brackets, so [Int] is a list of integers.
Each of these types maps straightforwardly to JavaScript, so you can just return plain old JavaScript objects in APIs that return these types. Here’s an example:
import express from 'express';
import { createHandler } from 'graphql-http/lib/use/express';
import {
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLFloat,
GraphQLInt,
GraphQLList,
} from 'graphql';
// Construct a schema.
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
quoteOfTheDay: {
type: GraphQLString,
resolve: () =>
Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within',
},
random: {
type: GraphQLFloat,
resolve: () => Math.random(),
},
rollThreeDice: {
type: new GraphQLList(GraphQLInt),
resolve: () => [1, 2, 3].map((_) => 1 + Math.floor(Math.random() * 6)),
},
},
}),
});
const app = express();
app.all(
'/graphql',
createHandler({
schema: schema,
}),
);
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');If you run this code with node server.js and browse to http://localhost:4000/graphql you can try out these APIs.
These examples show you how to call APIs that return different types. To send different types of data into an API, you will also need to learn about passing arguments to a GraphQL API.