---
title: Up Your API Game with GraphQL
description: About to start your next IT project? Use GraphQL to make your APIs flexible, powerful, and easy to work with.
image: https://blog.avenuecode.com/hubfs/Screen%20Shot%202019-08-14%20at%205.23.59%20PM.png
---

[AvenueCode.com](https://avenuecode.com) [News](https://avenuecode.com/news) [Contact](https://avenuecode.com/contact)

[![Avenue Code Snippets Logo](https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/AC-Snippets---Black.png)](https://blog.avenuecode.com/?hsLang=en-us) *menu*

- Technology
  
  [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us) [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us) [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us) [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us) [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
  
  [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us) [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us) [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us) [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

- [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us)
- [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us)
- [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us)
- [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us)
- [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us)
- [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us)
- [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us)
- [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

# [Up Your API Game with GraphQL](https://blog.avenuecode.com/up-your-api-game-with-graphql)

- [Tweet](https://twitter.com/share)

*perm\_identity* [Leandro Rezende Pinheiro](https://blog.avenuecode.com/up-your-api-game-with-graphql/author/leandro-rezende-pinheiro?hsLang=en-us)

*schedule* 8/28/19 2:00 PM

It's good practice to start new IT projects by considering how to easily and quickly consume and display data, and one of the first steps is creating or choosing the right API for your business. So why not choose an API that's a universal query language and provides a modern approach to accessing your data sources?

With its growing popularity, you have probably already heard about GraphQL, another great tool that Facebook developers make available to the world in addition to React. GraphQL was developed internally by Facebook in 2012 before being released to the public in 2015.

##### Advantages of GraphQL

1.  A single endpoint.
2.  No more over-fetching. 
3.  No more under-fetching.
4.  Display changes in real time.
5.  Access multiple data sources from a single point.
6. Front-end teams can easily test their applications by mocking up the required data structures. 
7.  Services usually respond using JSON,  which is easy to read and debug.
8.  Works with other JavaScript-based libraries and frameworks, such as Vue, Angular, and others.
9.  Can be used with any back-end framework or programming language.

##### GraphQL vs Rest

Let's take a look at the Rest call image below:

![null](https://lh3.googleusercontent.com/paNRNdSDBwrKdrlDjgpV2ANurDeEGv55eW-Fq9gg9ey65ci1E_htyf6crVaGVt9IHIYwX9qjWAG4iIi751TUMMiegIpg7HYlEsPABf7QFoxtxlCYeYCyyT6v6C4u8Y_NBpQ3EOQb)

Image courtesy of [How to GraphQL](https://www.howtographql.com/basics/1-graphql-is-the-better-rest/)

As [How to GraphQL](https://www.howtographql.com/basics/1-graphql-is-the-better-rest/) explains, "With REST, you have to make three requests to different endpoints to fetch the required data. You’re also *overfetching* since the endpoints return additional information that’s not needed."

One solution used in Rest API is query parameters. It works, but it requires complex logic and has no flexibility. Furthermore, working in this way slows the whole process of developing other data endpoints.

**How GraphQL Works in the Same Situation**

 

![null](https://lh5.googleusercontent.com/wbR6Cn2n9CtclyYEL9apbN21Y1Owkbd518bnftpzGdRSwCGuEeHBRNOs3oYM6RDDpbdHMHyZXVBHFJ8NRfjTM-XTiIwifxgZgBxxHvUtFEU_9uGsHfX3MHLhZaG-rxwQhf1IfqAH)

Image courtesy of [How to GraphQL](https://www.howtographql.com/basics/1-graphql-is-the-better-rest/)

Much simpler, don't you think?

##### How it Works

The syntax is simple and easy to understand. Developers who are familiar with JSON will quickly adapt to GraphQL. Look at the image below to see what this query returns.

![null](https://lh4.googleusercontent.com/RSqaptPUGlmdMMDE4HzYwYxfsK0--gOr6A6zqeYyG0LOomZ8MO_Has83dIFu6FoeITUvOzrvAKDHsTTn8d8XT3jVWwCwnYUC6hBLX3bI4FTPbP-yr5Rc_qUCN0cpCFG7J8GE1XVF)

 

##### **Schema & Type System**

GraphQL's Schema Definition Language (SDL) serves as the contract between the client and the server to define how a client can access the data.

**BASIC TYPES**

    String   
     Int  
     Float  
     ID  
     Boolean

**OPERATION TYPES**

   **Queries:** are data requests to the server based on your needs.

   **Mutations:** are used to insert, update, or delete data.

  ** Subscriptions:** push data from the server to the clients who chose to listen to real-time messages from the server.

**RESOLVERS**

> Resolvers provide the instructions for turning a GraphQL operation into data. Resolvers are organized into a one to one mapping to the fields in a GraphQL schema. - [Apollo Docs](https://www.apollographql.com/docs/apollo-server/essentials/data/)

##### **GraphQL Best Practices**

The following recommendations are brief paraphrases of the best practices listed on [the GraphQL website](https://graphql.org/learn/best-practices/). 

### HTTP

Avoid creating a suite of URLs. GraphQL supports this, but having a suite of URLs makes it harder to access GraphQL tools like the IDE, and you will also have other endpoints, which goes against the main idea behind GraphQL.

### JSON (with GZIP)

In a production GraphQL service, it's recommended that GZIP compression is enabled. So in client requests, we can set in the header:

```
Accept-Encoding: gzip
```

### Versioning

As with any other API, you can start versioning your GraphQL Project, but usually you have to do this when you have limited control over the data that is returned or when you have new features.

GraphQL only returns what is explicitly requested, so new capabilities can be added via new types and new fields on those types without introducing a big change in the code.

### Nullability

By default, all types in GraphQL are nullable and can go awry in a networked service backed by databases and other services.

### Pagination

The GraphQL type system allows for some fields to return [lists of values](https://graphql.org/learn/schema/#lists-and-non-null) but leaves the pagination of longer lists of values up to the API designer.

Ultimately, designing APIs with feature-rich pagination led to a best practice pattern called "Connections."

### Server-Side Batching & Caching

A naive GraphQL service can be very "chatty" or repeatedly load data from your databases. A good way to handle that is to collect multiple requests and later dispatch them in a single request.

A good tool is  [Facebook DataLoader.](https://github.com/graphql/dataloader)

##### Some Front-End Clients to Make Your Life Easier

1. Relay
2. Apollo Client

### ** Some advantages: **

         Data fetching  
         Caching logic  
         Easier pagination

##### GraphQL Examples for Two Different Scenarios

Below, I will give two very brief examples of GraphQL implementations, one for the flow and the other for the source code.

**CONSUMING AND PROVIDING DATA WITH APOLLO/GRAPHQL IN AN ORACLE DATABASE**

![LP image](https://blog.avenuecode.com/hs-fs/hubfs/LP%20image.png?width=720&name=LP%20image.png)

**Back-End Provider**

First, you need to define your endpoint:

```
const schema = graphqlTools.makeExecutableSchema({typeDefs, resolvers});    graphqlAC.use('/graphql', graphql({        graphiql: true,        schema    }));
```

 Second, define your types:

```
const typeDefs = `    type Post {        identifier: Int!,        title: String!     },`}
```

 Then, define resolvers and operations:

```
const resolvers = {        Query: {            posts(root, args, context, info) {                return getAllPosts();             },        },    };
```

 Finally, define your business logic implementation method to get data from the Oracle database.

```
    async function getAllPosts() {        let sql = 'select * from posts';               const result = await database.simpleExecute(sql);        let allPosts = [];                for (let r of result.rows){            const newTitle = {"identifier": r.IDENTIFIER, "title": r.TITLE};                            allPosts.push(newTitle);        }        return allPosts;     }
```

**Front-End Consumer**

In your React application, you must connect your app component, wrapping it with the ApolloProvider tag:

```
const client = new ApolloClient({ uri: 'http://localhost:5000/graphql' });<ApolloProvider client={client}>   <App /></ApolloProvider>
```

Then consume data from the GraphQL API with Apollo from a functional component:

```
const GET_MOTIVO = gql`{ posts {    identifier    title }}`const Apollo = () => ( <Query query={GET_MOTIVO}>  {({ loading, error, data }) => {     if (loading) return <div>Loading...</div>;      if (error) return <div>Error :(</div>;        return data.motivos.map(({ identifier , title }) => (       <div key={identifier}>         <p>{`${identifier}: ${title}`}</p>       </div>  )); }} </Query>
```

## QRAPHQL WORKING WITH MONGODB

#### Back-End Provider 

As with the fist scenario, we start by defining an endpoint.

```
app.use('/graphql',    graphqlHttp({   schema : graphiqlSchema,   rootValue: graphilResolvers,   graphiql: true }));
```

 Next, we define our Schema, then our Queries.

```
type Event {    _id: ID!    title: String!    description: String    price: Float!    date: String!    creator: User!}type RootQuery{ events: [Event!]!}
```

 Finally, we define our resolvers.

```
events: async () => { try {   const events = await Event.find();    return events.map(event => {     return event; }); } catch(err) {   throw err; } },
```

**Front-End Without a Client**

The following example shows how to consume a GraphQL service without a client:

```
fetchEvents() { const requestBody = {  query: `   query {    events {       _id       title       date       description       price       creator {         _id         email       }    } } ` };  fetch('http://localhost:5000/graphql', {   method: 'POST',   body: JSON.stringify(requestBody),   headers: {   'Content-Type': 'application/json', }  }).then(res =>{     if(res.status !== 200 && res.status !== 201){     throw new Error ('Failed');}  return res.json();}).then(resData => {        const events = resData.data.events;       this.setState({ events : events});} }).catch(error => {    console.log(error); });}
```

##### Conclusion

The main goal of the two different scenarios above is to demonstrate how flexible, powerful, and easy to use your APIs can be with GraphQL. So don't be afraid to use GraphQL in your next project--at least make one MVP to try it out. Be brave!

## **References/Further Reading:**

For references and further reading, I recommend that you check out: 

1. [GitHub GraphQL dataloader](https://github.com/graphql/dataloader)

2. [GitHub relayjs](https://github.com/relayjs)

3. [The New York Times - Now on Apollo](https://open.nytimes.com/the-new-york-times-now-on-apollo-b9a78a5038c)<https://open.nytimes.com/the-new-york-times-now-on-apollo-b9a78a5038c>

4.[GraphQL Best Practices](https://graphql.org/learn/best-practices/)

5. [React, Relay and GraphQL: Under the Hood of The Times Website Redesign](https://open.nytimes.com/react-relay-and-graphql-under-the-hood-of-the-times-website-redesign-22fb62ea9764)<https://open.nytimes.com/react-relay-and-graphql-under-the-hood-of-the-times-website-redesign-22fb62ea9764>

6. [React and GraphQL at the NYTimes](https://softwareengineeringdaily.com/2018/10/22/react-and-graphql-at-the-nytimes/)

7. [Introduction to GraphQL](https://graphql.org/learn/)

 

---

### Author

# Leandro Rezende Pinheiro

 Leandro Pinheiro is a UI Engineer at Avenue Code. In addition to being addicted to web application solutions, he is a movie marathonist and a music lover who enjoys having a good beer by his side.

---

### Related Posts

### Building Accessible Web Applications

[READ MORE](https://blog.avenuecode.com/building-accessible-web-applications?hsLang=en-us)

### How the Mulesoft JWT Validation Policy Works

[READ MORE](https://blog.avenuecode.com/mulesoft-jwt-validation-policy-works?hsLang=en-us)

### How to Use Redis Cache to Prevent DDoS Attacks

[READ MORE](https://blog.avenuecode.com/use-redis-cache-to-prevent-attacks?hsLang=en-us)

### Using Spring Webflux for REST APIs: Annotated and Functional Endpoints

[READ MORE](https://blog.avenuecode.com/using-spring-webflux-for-rest-apis-annotated-and-functional-endpoints?hsLang=en-us)

### Leave a Comment!

### Avenue Code Social

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Blog/facebook.png?t=1486470796564)](https://www.facebook.com/avenuecode)

[![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Blog/twitter.png?t=1486470796842)](https://twitter.com/AvenueCode)

[![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png?t=1486470796556)](https://www.linkedin.com/company/avenue-code)

### Newsletter

Want to stay on top of all tips and news from Avenue Code?

### Popular Snippets

![Primary Logo AvenueCode Inverted.png](https://blog.avenuecode.com/hs-fs/hubfs/Images/Logos/Primary%20Logo%20AvenueCode%20Inverted.png?width=1104&name=Primary%20Logo%20AvenueCode%20Inverted.png "Primary Logo AvenueCode Inverted.png")

### About Us

- [Who We Are](https://www.avenuecode.com/who-we-are)
- [What We Do](https://www.avenuecode.com/what-we-do)
- [Portfolio](https://www.avenuecode.com/portfolio)
- [Partners](https://www.avenuecode.com/partners)
- [News](https://www.avenuecode.com/news)
- [Events](https://www.avenuecode.com/events)
- [Blog](https://blog.avenuecode.com/)
- [Contact](https://www.avenuecode.com/contact)

### Our Offices

San Francisco

[+1 415 766 4178](tel:+553125161448) [ac.inquiries@avenuecode.com](mailto:brazil.info@avenuecode.com)

Belo Horizonte

[+55 31 2516 1448](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

São Paulo

[+55 11 3205 3232](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

### We're Hiring!

- [Belo Horizonte](https://www.avenuecode.com/who-we-are)
- [New York](https://www.avenuecode.com/what-we-do)
- [San Francisco](https://www.avenuecode.com/portfolio)
- [São Paulo](https://www.avenuecode.com/partners)

---

©2015 - 2017 Avenue Code

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Icons/facebook-2.png)](https://www.facebook.com/avenuecode) [![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Icons/twitter-2.png)](https://twitter.com/AvenueCode) [![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Icons/linkedin-2.png)](https://www.linkedin.com/company/avenue-code) [![Glassdoor Icon](https://blog.avenuecode.com/hubfs/Images/Icons/glassdoor-icon-1.png)](https://www.glassdoor.com/Overview/Working-at-Avenue-Code-EI_IE456173.11,22.htm) [![YouTube Icon](https://blog.avenuecode.com/hubfs/Images/Icons/youtube-2.png)](https://www.youtube.com/user/AvenueCodePlay)

Please enable JavaScript to view the [comments powered by Disqus.](http://disqus.com/?ref_noscript)

© 2026 Avenue Code

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Leandro Rezende Pinheiro",
    "url" : "https://blog.avenuecode.com/author/leandro-rezende-pinheiro"
  },
  "dateModified" : "2019-08-28T17:00:01.647Z",
  "datePublished" : "2019-08-28T17:00:00.000Z",
  "headline" : "Up Your API Game with GraphQL",
  "image" : [ "https://blog.avenuecode.com/hubfs/Screen%20Shot%202019-08-14%20at%205.23.59%20PM.png" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.avenuecode.com/up-your-api-game-with-graphql",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_LOGO%20HORIZONTAL%20group%201-7.png"
    },
    "name" : "Avenue Code"
  }
}
```