artCode

Introduction to GraphQL: Basic guide with Strapi support

GraphQL has revolutionized the way we interact with APIs, allowing flexible requests and obtaining precise data in a single endpoint.

Tags

  • Javascript
  • Node.js

Published

Reading Time

4 min
Cover image for Introduction to GraphQL: Basic guide with Strapi support

Why GraphQL?

With GraphQL, developers can request exactly the data set they need, nothing more and nothing less. This "ask for what you need" is a deviation from the REST model, where you receive rigidly structured data that often includes unnecessary information.

Here are some distinctive features of GraphQL:

  • Specific Requests: Precision in requesting specific fields on objects.
  • Data Aggregation: Ability to aggregate requests from multiple sources in a single call.
  • Network Efficiency: Minimizes transmitted data by eliminating overhead.
  • Agile Development: Facilitates frontend development thanks to the ability to modify queries without backend adjustments.

To introduce GraphQL and show some of its features, in this guide we will use Strapi. Strapi is a headless CMS that natively supports TypeScript and GraphQL.

Installing Strapi with TypeScript

Terminal
npx create-strapi-app@latest project-name --ts --quickstart cd project-name

This setup initializes a Strapi project using TypeScript, offering both advantages in terms of security and advanced pre-settings that facilitate development and maintainability.

Integrating GraphQL in Strapi

Positioning yourself in the correct directory, as shown in the previous code example, let's proceed by installing the GraphQL plugin

Terminal
npm install @strapi/plugin-graphql

After installing the plugin, it needs to be configured.

Add or modify the config/plugins.ts file (create it if it doesn't exist) with the following code:

JavaScript
// config/plugins.ts const config = { graphql: { enabled: true, }, }; export default config;

This plugin will allow Strapi to handle GraphQL queries and mutations automatically.

Creating a Content-Type in Strapi

Strapi manages its content through the "Content-Types Builder", which can be managed both through code by interacting with Strapi's structure itself, and through its interface.

In this case, through the interface's "Content Manager", create a new content-type called Articles.

Then, create two fields: Title and Content (of type Text). This way, we can use this Content-Type for our queries/mutations and manage our data set.

Queries and Mutations in GraphQL

GraphQL distinguishes itself in two fundamental operations: queries and mutations.

Queries: Queries are used to read or retrieve values. They don't modify data, making them safe and idempotent operations (that is, a query executed multiple times produces the same result without side effects).

Terminal
// graphql query { articles { data { attributes { title content } } } }

Mutations: Unlike queries, mutations are used to write or modify data. Each mutation can also have side effects (like sending an email notification after creating an article).

Terminal
mutation { createArticle(data: {title: "Introduction to GraphQL", content: "Where art meets code"}) { data { id attributes { title content } } } }

The previous code shows us how to create a new entity with a custom Title and Content.

Mutations are used to create, modify and delete data sets directly connected to our database.

Below, the example shows a mutation that performs an update of the article with ID 1.

Terminal
// graphql mutation { updateArticle(id: 1, data: {title: "Updated GraphQL - artCode", content: "GraphQL and Strapi: a dynamic duo."}) { data { attributes { title content } } } }

Furthermore, thanks to mutations, knowing the id of the entity we want to delete, it will be easy to also perform a DELETE operation on it.

Below is an example:

Terminal
// graphql mutation { deleteArticle(id: 1) { data { id } } }

Using GraphQL with Strapi greatly facilitates API management, allowing detailed and specific CRUD operations through a simple and powerful interface.

The provided mutation examples illustrate how to manipulate data effectively, making your applications more flexible and performant.

Returning to our example, once Strapi is started, the interface will be accessible via the address http://localhost:1337/admin

Note: Strapi implements an advanced and flexible system for user and permission management, which also regulates access to endpoints. To execute queries or mutations on a specific content type, it is essential to configure the appropriate authorizations in the Strapi control panel.

Below is an example of a fetch in Javascript to retrieve data through GraphQL from our Strapi:

JavaScript
// GraphQL query definition const query = ` query { articles { data { attributes { title content } } } } `; // Async function to execute the fetch request async function fetchArticles() { const options = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query }) }; try { const response = await fetch('http://localhost:1337/graphql', options); const data = await response.json(); console.log(data); return data; } catch (error) { console.error('Error fetching data: ', error); } } // Function call fetchArticles();

Adopting GraphQL and Strapi not only optimizes and simplifies API management but also transforms the way you interact with data, making every query precise and efficient. This integration eliminates complexity and accelerates development, allowing you to focus on creating innovative features rather than data management.

Can't wait to experiment with this powerful combination in your projects? Your next API could be simpler and more performant than you imagine!

Introduction to GraphQL: Basic guide with Strapi support | artCode