GraphQL APIs and the Future of Front-End Development
Tags: graphql, appwrite, hackmamba, frontend
Published: 2023-03-02 10:37:18


GraphQL is a powerful query language and runtime that enables developers to create efficient and flexible APIs. Its popularity among developers has risen due to its ability to handle complex queries and provide improved user experiences. As the future of front-end development is heavily influenced by how we consume and utilize APIs, GraphQL is expected to play a significant role in shaping it. 
In this article, we will learn about GraphQL, its benefits, its impact on the future of front-end development, and how it works with Appwrite's API protocol through a code example.


## Prerequisites

To follow this article, we need the following:


- Prior knowledge of Vue and project installed on our local machine
- Docker installed on our machine to check the version of our Docker, we will use the command `docker --version`. If Docker is not installed, we can install it from [Docker documentation](https://docs.docker.com/get-docker/). Click this [link](https://runnable.com/docker/install-docker-on-macos) for a better explanation of how to install it on macOS.
- A running Appwrite instance (check out this article to [create a local Appwrite instance](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba))
- Tailwind CSS installed in our Vue project

## What is GraphQL?

[GraphQL](https://graphql.org/learn/) is a query language and runtime for creating and executing API queries. It was created by the Facebook team in 2012 and was open-sourced in 2015. It provides the schema of the Data in the API and allows users to specify the required data structure they need and the server will only return the requested data. This can decrease the amount of data transmitted over the network and make working with APIs with complex data schemas, much easier.

## A Critical Appraisal of GraphQL

One of GraphQL's advantages is its adaptability. Clients can specify exactly the data they require in a single request, making it more efficient than a REST API, which may require multiple requests to different endpoints to gather the same information. Furthermore, GraphQL supports real-time updates and subscriptions, which enables developers to create dynamic and responsive applications. Additionally, its ability to handle complex relationships is an invaluable asset as it allows nested queries, which brings the possibility of retrieving related data in one request.

## Advantages of using GraphQL

GraphQL is an increasingly popular API for front-end development that offers a variety of advantages, such as: 


- **Improved Performance**

GraphQL increases our application performance by reducing the number of queries and providing us with the data we need.


- **Better Development Tool** 

GraphQL provides developers with different tools that make development and debugging easier. We can also test our GraphQL applications with those tools; some of the tools are GraphiQL, Apollo Studio, etc.


- **Strong Type System**

GraphQL provides a strong data typing system, better documentation, and simpler tooling.

- **Easy Integration and Maintenance**

GraphQL is simple to integrate into existing systems, allowing us to start using it immediately without significantly modifying our current infrastructure.

## GraphQL vs Rest API

GraphQL and REST are the most widely used architectural patterns for developing web services. While they have some similarities, they also have significant differences that must be considered when deciding between them.

GraphQL is a manipulation language for interacting with an API that retrieves data from a server or database and displays it in our application. With GraphQL, we can specify the data we need and the server will return only the requested data, which makes development easier and more flexible than Rest API.

GraphQL is [schema-based](https://www.apollographql.com/docs/apollo-server/schema/schema), meaning we strictly define what goes to the server and what can leave the server. The schema is a compelling security point of view.

**Rest API**
[REST API](https://www.edureka.co/blog/what-is-rest-api/) is a software architecture method for creating web services. It outlines a collection of restrictions and specifications for building web services used to communicate with other systems and web applications over HTTP. It manipulates resources via HTTP methods, including GET, POST, PUT, DELETE, and returns JSON or XML data.

Here are other side-by-side comparisons of GraphQL and Rest

| GraphQL                                                                                                                                 | Rest                                                                              |
| --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| It has a single endpoint (post/graphql)                                                                                                 | Rest has multiple endpoints (POST/form, GET/user)                                 |
| GraphQL reduces the number of necessary API calls to ensure we get the right amount of data; this helps improve application performance | It has slow performance due to under-fetching data, and unnecessary API calls     |
| It is client driven                                                                                                                     | It is server-driven                                                               |
| It lacks an automatic caching mechanism and instead uses a library that is built on top of it                                           | It uses caching automatically without any library                                 |
| GraphQL complicates the handling of HTTP status codes to identify errors                                                                | Rest is easy to debug because it uses HTTP status codes to identify errors easily |
| It has a built-in meta validation                                                                                                       | The validation is implemented manually                                            |

Finally, when deciding between GraphQL and REST for web services, developers should consider the type of application and data access requirements. If a large amount of data must be retrieved and updated in real time, GraphQL is the best option. However, if a simple, read-only application is being developed, REST is the better choice.

**Limitations of GraphQL**
While GraphQL is an efficient query language that simplifies the process of obtaining data from an API, it does have certain limitations. 


- GraphQL makes it challenging to create complex queries that require data from multiple sources or relational databases.
- It cannot be used to access data outside of the API, making it less suitable for applications that require external data sources.
- GraphQL does not provide built-in security features; as developers, we must implement our authentication and authorization mechanisms to secure our GraphQL API.
- Error handling is complicated in GraphQL since it doesn’t use HTTP status codes like REST API.


## Future of GraphQL API in Front-End Development

The GraphQL API has a promising future in front-end programming. Due to its capacity to manage various data sources, reduce data over- or under-fetching, and make optimal use of network bandwidth, it is anticipated to grow in popularity. The availability of more APIs means the development process is getting quicker and more effective. One is the capacity to query many databases with a single query effectively. 

We can use GraphQL to create and maintain robust applications in our various languages and frameworks, including React, Angular, Vue, and Node.js.

GraphQL is essential to [backend-for-frontend](https://medium.com/tech-tajawal/backend-for-frontend-using-graphql-under-microservices-5b63bbfcd7d9) architecture because it allows clients to request the data they require, enabling developers to create backends specifically designed to meet the requirements of frontends like web apps. It offers a reliable and adaptable method to manage a data relationship, which can simplify the implementation of challenging BFF features.

## Powering GraphQL with Appwrite's API Protocol

By integrating the [Appwrite API](https://appwrite.io/docs/client/locale) server with our GraphQL API, we can leverage Appwrite's API protocol to power our GraphQL implementation. This integration also enables using Appwrite's administration tools for authentication, authorization, rate limiting, and logging to manage and secure our GraphQL API. The API protocol provided by Appwrite also enables the development of unique APIs to access data from other services. For instance, developers can create an API that we can use to retrieve data from a third-party database. It also offers a unified API gateway to gather and manage numerous APIs, including our GraphQL API, in one location.

## Example of Using Appwrite with GraphQL

We will learn how to utilize Appwrite with GraphQL in this example; however, before moving on to the next step, there are a few things we need to understand and set up. All of the prerequisites are stated in the prerequisites section.

If all the requirements have been completed, let's create a new Appwrite project. Using the [Appwrite Locale API](https://appwrite.io/docs/client/locale?sdk=graphql-default#localeListCurrencies), we will create a simple app that displays a country's currency symbol, name, plural, and decimal digits for all major and minor currencies.


## Creating a New Appwrite Project

After creating our locale Appwrite instance and creating an account with Appwrite, we will be redirected to a page to create a new project:

![](https://paper-attachments.dropboxusercontent.com/s_FAA126D11578696CF651935173EF9B28FA574D302BCE745E6CCCA72D636DAD43_1675366828721_Screenshot+2023-02-02+at+20.39.44.png)


 
In this section, we will name our project `currency-app` when we click on the “Create project” button, we will be redirected to our dashboard. 

Appwrite SDKs make it easier to add any platform we want to use; for instance, we have the Web App, Flutter App, Apple App, and Andriod App. Select the Web App platform since we are building for the web:

![](https://paper-attachments.dropboxusercontent.com/s_FAA126D11578696CF651935173EF9B28FA574D302BCE745E6CCCA72D636DAD43_1675366896278_Screenshot+2023-02-02+at+20.41.15.png)

![](/static/img/pixel.gif)


When we click on the Web App platform, we will be redirected to a page to register our web app:

![](https://paper-attachments.dropboxusercontent.com/s_FAA126D11578696CF651935173EF9B28FA574D302BCE745E6CCCA72D636DAD43_1675288837696_Screenshot+2023-02-01+at+22.58.30.png)


The next step is to get the Appwrite SDK we can choose our preferred method of adding Appwrite to our project:


![](https://paper-attachments.dropboxusercontent.com/s_FAA126D11578696CF651935173EF9B28FA574D302BCE745E6CCCA72D636DAD43_1675289181814_Screenshot+2023-02-01+at+23.04.59.png)


To install Appwrite in our Vue project, use the command below:


```javascript
    npm install appwrite 
```


After installing Appwrite, the next step is to configure our Appwrite web SDK:


  

```Javascript
  const client = new Client();
    
    client
        .setEndpoint('http://localhost:90/v1')
        .setProject('PROJECT ID');
```

Go to the project overview in the Appwrite console and click on settings to get the project ID. 


![](https://paper-attachments.dropboxusercontent.com/s_FAA126D11578696CF651935173EF9B28FA574D302BCE745E6CCCA72D636DAD43_1675366339025_Screenshot+2023-02-02+at+20.28.04.png)


We can also get the project ID when creating a new web project in Appwrite; see the example below.

![](https://paper-attachments.dropboxusercontent.com/s_FAA126D11578696CF651935173EF9B28FA574D302BCE745E6CCCA72D636DAD43_1675335806918_Screenshot+2023-02-02+at+11.59.49.png)



## Creating Application Layout

The next step after installing and configuring Appwrite is to construct our application layout, which is where we will display the currency data we are collecting from the API.

``` html

<template>
  <main>
    <section class="banner-image">
    </section>
    <section class="text-gray-600 body-font">
      <div class="container px-5 py-16 mx-auto">
        <div class="flex flex-col text-center w-full mb-20">
          <h2 class="text-xs text-indigo-500 tracking-widest font-medium title-font mb-1">Currency Application</h2>
          <h1 class="sm:text-3xl text-3xl font-bold title-font text-gray-900">List of Country Currencies and Symbols
          </h1>
        </div>
        <div class="flex flex-wrap -m-4">
          <div v-for="(currency, index) in currencies" :key="index" class="p-4 md:w-1/3">
            <div class="flex rounded-lg h-full bg-gray-100 p-8 flex-col">
              <div class="flex items-center mb-3">
                <div
                  class="w-16 h-16 mr-3 inline-flex items-center justify-center text-gray-800 border border-gray-800 bg-white flex-shrink-0">
                  <p class="text-black text-2xl">{{ currency.symbol }}</p>
                </div>
                <h2 class="text-gray-900 text-lg title-font font-medium">{{ currency.name }}</h2>
              </div>
              <div class="flex-grow">
                <h2 class="text-gray-900 text-lg font-bold">{{ currency.name }}</h2>
              </div>
            </div>
          </div>

        </div>
      </div>
    </section>
  </main>
</template>
```
 

The following step is to import the Client and GraphQL classes into our application. `CurrencyApp.vue` from the Appwrite library. This will enable us to leverage GraphQL capabilities from Appwrite in our web application:


```Javascript
    <script>
    import { Client, Graphql } from "appwrite";
    const client = new Client();
    client
      .setEndpoint('http://localhost:90/v1')
      .setProject('PROJECT ID');
    const graphql = new Graphql(client);
    export default {
      name: "CurrencyApp",
    </script>

```

## Fetching the Currencies from Appwrite Locale API

In the following example, we create a data property that returns the list of currencies and then create a GraphQL query in our Vue component to get the Appwrite Locale API's list of currencies:
  

```javascript
  <script>
    import { Client, Graphql } from "appwrite";
    const client = new Client();
    client
      .setEndpoint('http://localhost:90/v1')
      .setProject('PROJECT ID');
    const graphql = new Graphql(client);
    export default {
      name: "CurrencyApp",
      data() {
        return {
          currencies: [],
        };
      },
      methods: {
        async fetchCountryCurrencies() {
          try {
            const currencyQuery = (await graphql.query({
              query:
                ` query{
              localeListCurrencies {
              total
              currencies {
                code
                symbol
                name
             }
            }
        }`
            }));
            this.currencies = 
           currencyQuery.data.localeListCurrencies.currencies;
          } catch (err) {
            console.error(err);
          }
        },
      },
      mounted() {
        this.fetchCountryCurrencies();
      },
    };
    </script>
```

The web application's final appearance is shown in the picture below.


![](https://www.dropbox.com/s/gs8wxo73nh7l82h/currency-app.gif?raw=1)


[https://www.dropbox.com/s/gs8wxo73nh7l82h/currency-app.gif?dl=0](https://www.dropbox.com/s/gs8wxo73nh7l82h/currency-app.gif?dl=0)

## Conclusion

[GraphQL APIs](https://docs.github.com/en/graphql) can transform front-end development by offering a more effective and simplified approach to getting data, significantly improving user experience, and opening up new doors for innovation in the web development industry. This post introduced us to GraphQL and provided an example of how to use Appwrite with GraphQL.



## Resources
- [Introduction to GraphQL](https://graphql.org/)
- [Advantages of using GraphQL](https://www.optisolbusiness.com/insight/top-5-advantages-of-graphql)
- [GraphQL best practices](https://graphql.org/learn/best-practices/)
- [GraphQL crash course](https://www.howtographql.com/) 
- [Why You Should Use GraphQL APIs in Your Next Project](https://www.dropbox.com/scl/fi/88xiyj1krczbrhuycg15x/Why-You-Should-Use-GraphQL-APIs-in-Your-Next-Project.paper?dl=0&amp;rlkey=jwjpkzwku3rl2xxfo3m7bhbqf) 
- [Build an Ecommerce Product Catalog with Nuxt.js and GraphQL](https://www.dropbox.com/scl/fi/d0r4gwybs0ixzbj5w7f48/Build-an-E-commerce-Product-Catalog-with-Nuxt.js-and-GraphQL.paper?dl=0&amp;rlkey=9u035mvu7sc70ojb3tla6mhrz)

[](https://graphql.org/)