Defining types for your GraphQL API
Tags: graphql
Published: 2020-01-24 15:47:24

---
title: Defining types for your GraphQL API
published: true
date: 2020-01-22 18:04:48 UTC
tags: graphql
canonical_url: https://blog.logrocket.com/defining-types-for-your-graphql-api/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/b9x19s9fahh4tbgiihsr.png
---
**Written by [Adhithi Ravichandran](https://blog.logrocket.com/author/adhithiravichandran/)**✏️

[GraphQL](https://graphql.org/) is a query language for your API. It was [open-sourced](https://github.com/graphql) by Facebook in 2015 and ever since then gained immense popularity as an alternative to REST. Companies like [PayPal](https://medium.com/paypal-engineering/graphql-a-success-story-for-paypal-checkout-3482f724fb53), [Shopify](https://help.shopify.com/en/api/graphql-admin-api), [GitHub](https://developer.github.com/v4/), and many other leading companies in tech are using GraphQL today. GraphQL was created to have better communication between the client and the server. In this blog post, we will learn about GraphQL types and how they are used to construct a GraphQL schema.

## Strongly typed schema

GraphQL has a [strongly typed](https://en.wikipedia.org/wiki/Strong_and_weak_typing) schema. This means that the schema acts as a contract between the client and the server. This is one of the biggest benefits of using GraphQL.

### Benefits of a strongly typed schema

- **Schema serves as a contract** — With a strongly typed schema, the schema serves as a contract between the client and server. The interaction between the client and server gets easier with this clearly defined schema. It reduces any miscommunication and potential delays that can otherwise occur in client/server interaction while consuming APIs
- **Early detection of errors** — In GraphQL, you can catch plenty of errors in the GraphQL editor during development stages. This is because any incorrect data passed to the API will be marked as an error, due to the strongly typed nature of the schema. This saves a lot of time and effort during the development cycle
- **Teams work independently** –Because everything is clearly defined in the schema and the strongly typed schema can also generate documentation that clients can use, frontend and backend teams can work independently

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## GraphQL scalar types

[Scalar types](https://graphql.github.io/graphql-spec/June2018/#sec-Scalars) are the primitive data types in GraphQL. Here are the primitive data types that GraphQL supports:

- [Int](https://graphql.github.io/graphql-spec/June2018/#sec-Int) – A signed 32-bit integer
- [Float](https://graphql.github.io/graphql-spec/June2018/#sec-Float) – A signed double precision floating point value
- [String](https://graphql.github.io/graphql-spec/June2018/#sec-String) – A UTF-8 character sequence
- [Boolean](https://graphql.github.io/graphql-spec/June2018/#sec-Boolean) – Represents true/false
- [ID](https://graphql.github.io/graphql-spec/June2018/#sec-ID) – Unique identifier

Let’s write a GraphQL object that has its own characteristics, and comprises of items, each with its own type:

```jsx
type BlogPost {
      id: ID
      title: String
      author: String
      numberOfLikes: Int
    }
```

In the example above, we have created a complex object of type _BlogPost_. The _BlogPost_ object contains an id, title of the post, author of the post, and the number of likes received. When you write the GraphQL schema, the first thing you’d do is define the types.

Since GraphQL is strongly typed and heavily relies on the types, these are defined at the beginning, before the creation of the schema.

Let’s look at some more types in GraphQL to understand this further.

## Enum type in GraphQL

GraphQL supports the _enum_ type and they work just like how they work in any other programming language. Enums allow you to validate that any argument can have one of the defined values. Enums are also a scalar type in GraphQL.

Here is an example of the enum type in GraphQL:

```jsx
enum BlogTopics {
  WEB,
  MOBILE,
  FRONTEND,
  BACKEND, 
  GENERAL
}
```

In the example, we have defined an enum of type _BlogTopics_. And this enum can have five values. The topics can be web, mobile, frontend, backend, or general. The _BlogTopics_ type is allowed to have any of these five values.

## List type in GraphQL

The GraphQL schema supports an extension of the scalar type to have a listen of items. It is as simple as adding square brackets around the type to make it a list of that type. For instance, if you want a list of integers, you can declare it as **int** which indicates that it is a list type.

Let’s add a list type to our original _BlogPost_ type:

```jsx
type BlogPost {
  id: ID
  title: String
  author: String
  numberOfLikes: Int
  comments: [String]
}
```

We have added an item for blog post comments, and it is a list of strings. This means it could hold multiple comments as a list. Lists are used frequently in GraphQL schema.

## Query and mutation type

A GraphQL schema can contain more than just the scalar types. The two most used types are [query and mutation types](https://graphql.org/learn/schema/#the-query-and-mutation-types).

**Every GraphQL service will have a query type.** This is the entry point to a GraphQL schema. The query in GraphQL represents what the client is asking for from the GraphQL API.

To learn more about GraphQL queries you can read the [blog post](https://dev.to/bnevilleoneill/graphql-queries-explained-in-simple-terms-4inc) I wrote detailing how queries are constructed in GraphQL.

Although every GraphQL service has a query type, it may or may not include a mutation type. GraphQL mutations are used to add/update/delete data. The clients can use available mutations to update the data. You can think of it like a POST request in the REST world.

Here is how you define the query and mutation types in the GraphQL schema:

```jsx
schema {
      query: Query
      mutation: Mutation
    }
```

In GraphQL, both the query and mutation types are treated just like any other data type.

Let’s look into some examples to understand these better. I am going to extend our previous example of type _BlogPost_ to include a query and mutation type:

```jsx
type Query {
  blog_info: [BlogPost]
}
```

In the example above, we have defined a query called _blog-info_. The query type is defined just like any other type in GraphQL. With this, we have now defined a new query _blog-info_ that the clients can use to retrieve data. It would return an array of data of type _BlogPost_.

Similarly, we can define mutation types as well:

```jsx
type Mutation {
  add_blog_post: (title: String, author: String, numberOfLikes: int) : BlogPost
}
```

Here the _add_blog_post_ mutation can be used to add new items to the _BlogPost_. It takes in _title, author,_ and _numberOfLikes_ as arguments.

Similarly, you can define several queries and mutations for your GraphQL API.

## Non-nullable fields

What’s cool about GraphQL types is that you can define types and decide if they can be nullable or not. I have tweaked our original _BlogPost_ type to include a non-nullable field. Notice below that there is an exclamation mark (!) beside the _ID_. This indicates that the ID can never be null.

```jsx
type BlogPost {
  id: ID!
  title: String
  author: String
  numberOfLikes: Int
}
```

By default, each of the scalar types can be set to null. By adding the exclamation mark we are setting a rule that the field can never be null. I like this feature because it defines a clear contract between the client and the server and eliminates any confusion while using the API.

## Combining list and non-null

For more complex schema definitions, we can combine lists and non-nulls in multiple ways. Let’s say you have a list type named `[myList]`. Here are the ways you can combine non-null with the list.

- If you want a list that cannot contain any null items then you can declare your list as `[myList!]`. This means that the items within the list cannot be null
- Alternatively, if you declare the list as `[myList!]`, with the non-null exclamation mark outside of the square brackets, it means something else. This indicates that null is not accepted but the list is allowed to be empty
- You can also declare your list as `[mylist!]!`. This is a stricter form of non-null. This means that the list cannot contain any non-null items, and the list cannot be null either

In our example below, the comments list cannot have any null items within it:

```jsx
type BlogPost {
  id: ID
  title: String
  author: String
  numberOfLikes: Int
  comments: [String!]
}
```

## Conclusion

I hope you enjoyed learning about GraphQL types. If you are interested in further learning about GraphQL and get a big picture overview of GraphQL, you can check out my course on [Pluralsight](https://app.pluralsight.com/library/courses/graphql-big-picture/table-of-contents) on GraphQL.

Other resources:

- [https://graphql.org/](https://graphql.org/)
- [https://graphql.org/learn/](https://graphql.org/learn/)
- [https://www.graphql.com/](https://www.graphql.com/)

If you have any comments, please post your comments below and share this post with your team and friends.

* * *
## 200's only ‎✅: Monitor failed and show GraphQL requests in production 

While GraphQL has some features for debugging requests and responses, making sure GraphQL reliably serves resources to your production app is where things get tougher. If you’re interested in ensuring network requests to the backend or third party services are successful, [try LogRocket.](https://www2.logrocket.com/signup-lr)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jd2amkhuiynfjf3i33qk.png)

[LogRocket](https://www2.logrocket.com/signup-lr) is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic GraphQL requests to quickly understand the root cause. In addition, you can track Apollo client state and inspect GraphQL queries' key-value pairs.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. [Start monitoring for free.](https://www2.logrocket.com/signup-lr)
* * *

The post [Defining types for your GraphQL API](https://blog.logrocket.com/defining-types-for-your-graphql-api/) appeared first on [LogRocket Blog](https://blog.logrocket.com).