Back to blog overview

May 8, 2023

How to Use GraphQL in RedwoodJS

Natalia Diaz

&

&

Software Engineer
Chula Vista, CA

## Using GraphQL in Full-Stack Applications


Have you struggled in a full-stack application to query all necessary data? Thought about which tools to use to make this process more efficient and readable? In my experience, I have found that GraphQL is an excellent query tool that establishes types, simplifies the data connection, and creates a more coherent code base.


[GraphQL](https://graphql.org/) provides a comprehensive description of the data in your API, grants developers the ability to request precise data they require without redundancy, and simplifies the process of modifying APIs as necessary.


## What is GraphQL?


GraphQL is a query language for [APIs](https://www.ibm.com/topics/api) that provides a more efficient and flexible alternative to [REST](https://restfulapi.net/). With REST, a developer will create multiple requests to the server to retrieve pieces of data to create, read, update, and delete or simply go through the CRUD actions. For example, a REST get request to read the requested data is the following:


```jsx

const sayHi = (req, res) => {

 res.send("Hi!");

};


app.get("/", sayHi)

```


GraphQL simplifies this by allowing the developer to specify the exact data needed in a single request. Developers can set up to receive the specific fields needed, subsequently reducing the amount of data transferred and improving performance.


For example, a simple GraphQL query is the following:


```graphql

 type User {

   id: Int!

   email: String!

   name: String

 }


 type Query {

   users: [User!]! @requireAuth

   user(id: Int!): User @requireAuth

 }

```


In an application [resolvers](https://graphql.org/learn/execution/) are functions accessing and manipulating data. For example, the following is a resolver function to find all users in the database.


```markdown

export const users: QueryResolvers['users'] = () => {

 return db.user.findMany()

}

```



GraphQL collects and organizes data from these resolvers and sends the response back to the developer. The query language is impartial to the data source used to obtain data and record modifications making it versatile in full-stack applications.


## Why Use GraphQL?


Using GraphQL as your query language offers many benefits, including:


- Simplifying your code base

- Organizing data into types

- Improving code readability

- Ensuring all data is statically typed

- Providing information on which queries the schema can support

- Returning data is easy to work with in JavaScript


With a query language, all the required information can be quickly accessed and manipulated. GraphQL queries can access both the properties of a single resource and the references between multiple resources. Unlike traditional endpoints, GraphQL APIs are organized by types and fields. For example, the following is a type Book correlating to the model Book with fields assigned a specific [data type](https://amplitude.com/blog/data-types).


```graphql

type Book {

 name: String

 description: String

 publisher: [Publisher]

}

```


Additionally, GraphQL is not bound to any particular database or storage engine; rather, it is backed by existing code and data.


Basically, GraphQL is like a superhero that creates a single API for your entire application, no matter what storage engine you're using, and makes querying easy to navigate.


## Using GraphQL in RedwoodJS


###Starting off your GraphQL in RedwoodJS


In [RedwoodJS](https://redwoodjs.com/), GraphQL comes pre-installed. To start off your application, you may first want to set up your schema. This file is designed to create your model table, noting the model’s fields and data types. For example:


```graphql

model User {

 id        Int      @id @default(autoincrement())

 email     String

 name      String

}

```


As you are building out your [schema](https://www.prisma.io/docs/concepts/components/prisma-schema), and setting up your application there are a few ways to go about establishing your queries. After your schema is compiled and a migration of your new table is sent to the database, RedwoodJS has a useful command that can really kick-start your application. Simply run:


```markdown

yarn rw g scaffold user

```


This one command has just created the elements needed to run basic queries, set up your resolvers, and establish CRUD actions in components and pages in your web folder involving your User model.


If you prefer to take your application development slower to customize your queries, components, and pages, or simply add an additional GraphQL query there is a second option. In RedwoodJS to create a GraphQL file inside your GraphQL folder, simply run the following command:


```markdown

yarn rw g sdl User

```


This command will create the bare bones of the file. The GraphQL file includes minimal types needed to query the information according to the model. These files can be as complex as needed adding detailed parameters and specificity about inputs and data types accepted.


This command will also create the correlated resolvers in your services folder.


Both of these commands will set up basic queries to start. The following is an example of what to expect:


```graphql

export const schema = gql`

 type User {

   id: Int!

   email: String!

   name: String

 }


 type Query {

   users: [User!]! @requireAuth

   user(id: Int!): User @requireAuth

 }


 input CreateUserInput {

   email: String!

   name: String

 }


 input UpdateUserInput {

   email: String

   name: String

 }


 type Mutation {

   createUser(input: CreateUserInput!): User! @requireAuth

   updateUser(id: Int!, input: UpdateUserInput!): User! @requireAuth

   deleteUser(id: Int!): User! @requireAuth

 }

`

```


As your application expands and specific queries are needed, you can easily alter and add to this file. For example, if a query was needed for usersWithComments it would be helpful to add on to type Query to include a section for usersWithComments.


### What else you can accomplish


The beauty of GraphQL is that it puts you in charge. You can create various types of queries to use throughout your application, which assists in organizing the data you're pooling and displaying. For instance, let's say you have a model for comments - you might want to display comments with responses attached or simply comments without any response. These can be distinct queries to suit your needs. The following is an example of the above instance:


```graphql

type Query {

   commentsWithResponse(

     reponseById: Int

     reponseByName: String

     commentById: Int

     commentByName: String

   ): [Comment!]! @skipAuth

   commentsWithoutResponse(

     reponseByName: Int

     reponseByName: String

     commentById: Int

     commentByName: String

   ): [Comment!]! @skipAuth

 }

```


In addition, you have the flexibility to customize your inputs. For example, in your User model, you may create an input to update the current user’s email. Thanks to your input and mutations, you can mold the input to update that data easily.


```graphql

input UpdateEmailInput {

   password: String!

   newEmail: String!

 }


type Mutation {

   updateEmail(input: UpdateEmailInput!): Boolean! @requireAuth

 }

```


## In Conclusion


GraphQL is a powerful tool for building efficient and flexible APIs. RedwoodJS makes it easy to use GraphQL in your web applications and provides a set of conventions and tools that make it easy to build scalable and maintainable applications.


Knowing how to set up and operate your GraphQL will result in your queries through your application being easily referenced, as well as improved performance. The next step of setup would be your resolvers working in Prisma. If you’d like to get more information about working in your Prisma files, [check out this for more information](https://www.codingzeal.com/post/how-to-use-redwood-with-prisma). Good luck building!


Photo by [Nail Gilfanov](https://unsplash.com/@ngilfanov?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/tree-laptop?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

Let's Chat

Are you ready to build something brilliant? We're ready to help.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
RedwoodJS Logo
RedwoodJS
Conference

conference
for builders

Grants Pass, Oregon • September 26 - 29, 2023
View All