GraphQL - Strapi Developer Documentation (2023)

By default Strapi create REST endpoints for each of your content-types. With the GraphQL plugin, you will be able to add a GraphQL endpoint to fetch and mutate your content.

# Usage

To get started with GraphQL in your app, please install the plugin first. To do that, open your terminal and run the following command:

Then, start your app and open your browser at http://localhost:1337/graphql (opens new window). You should see the interface (GraphQL Playground) that will help you to write GraphQL query to explore your data.

# Registration

Usually you need to sign up or register before being recognized as a user then perform authorized requests.

Mutation

You should see a new user is created in Users collection type in your Strapi admin panel.

# Authentication

To perform authorized requests, you must first get a JWT:

Mutation

Then on each request, send along an Authorization header in the form of { "Authorization": "Bearer YOUR_JWT_GOES_HERE" }. This can be set in the HTTP Headers section of your GraphQL Playground.

# Configurations

By default, the Shadow CRUD feature is enabled and the GraphQL is set to /graphql. The Playground is enabled by default for both the development and staging environments, however it is disabled in production. By changing the config option playgroundAlways to true, you can enable it.

Security limits on maximum number of items in your response by default is limited to 100, however you can change this on the following config option amountLimit. This should only be changed after careful consideration of the drawbacks of a large query which can cause what would basically be a DDoS (Distributed Denial of Service). And may cause abnormal load on your Strapi server, as well as your database server.

You can also setup any Apollo Server options (opens new window) with the apolloServer option. For example, you can enable the tracing feature, which is supported by the playground to track the response time of each part of your query. To enable this feature just change/add the "tracing": true option in the GraphQL settings file. You can read more about the tracing feature from Apollo here (opens new window).

You can edit these configurations by creating following file.

✋ CAUTION

Please note the setting for GraphQL tracing as changed and has been moved to apolloServer.tracing

Path — ./config/plugins.js

# Query API

In the section, we assume that the Shadow CRUD feature is enabled. For each model, the plugin auto-generates queries and mutations which just fit to your needs.

# Fetch a single entry

  • id: String

Query

# Fetch multiple entries

Query

# Fetch dynamic zone data

Dynamic zones are union types in graphql so you need to use fragments to query the fields.

(Video) What's new in v4: Rest and GraphQL APIs

Query

# Create a new entry

  • input: Object
    • data: Object — Values to insert

Mutation

The implementation of the mutations also supports relational attributes. For example, you can create a new User and attach many Restaurant to it by writing your query like this:

# Update an existing entry

  • input: Object
    • where: Object - Entry's ID to update
    • data: Object — Values to update

Mutation

You can also update relational attributes by passing an ID or an array of IDs (depending on the relationship).

Mutation

# Delete an entry

  • input: Object
    • where: Object - Entry's ID to delete

Mutation

# Filters

You can also apply different parameters to the query to make more complex queries.

  • limit (integer): Define the number of returned entries.

  • start (integer): Define the amount of entries to skip.

  • sort (string): Define how the data should be sorted.

  • publicationState (PublicationState): Only select entries matching the publication state provided.

    Handled states are:

    • live: Return only published entries (default)
    • preview: Return both draft entries & published entries
  • locale (string): Define the locale to fetch the content for, if the Internationalization (i18n) plugin is installed and localization is enabled for the content-type.

  • <field>:asc or <field>:desc

  • where (object): Define the filters to apply in the query.

    • <field>: Equals.
    • <field>_ne: Not equals.
    • <field>_lt: Lower than.
    • <field>_lte: Lower than or equal to.
    • <field>_gt: Greater than.
    • <field>_gte: Greater than or equal to.
    • <field>_contains: Contains.
    • <field>_containss: Contains sensitive.
    • <field>_ncontains: Doesn't contain.
    • <field>_ncontainss: Doesn't contain, case sensitive
    • <field>_in: Matches any value in the array of values.
    • <field>_nin: Doesn't match any value in the array of values.
    • <field>_null: Equals null/Not equals null

# Examples

Return the second decade of users which have an email that contains @strapi.io ordered by username.

Query

(Video) Strapi v4 Crash Course

Return the users which have been created after the March, 19th 2018 4:21 pm.

Query

# Shadow CRUD

To simplify and automate the build of the GraphQL schema, we introduced the Shadow CRUD feature. It automatically generates the type definition, queries, mutations and resolvers based on your models. The feature also lets you make complex query with many arguments such as limit, sort, start and where.

✏️ NOTE

If you use a local plugin, the controller methods of your plugin are not created by default. In order for the Shadow CRUD to work you have to define them in your controllers for each of your models. You can find examples of controllers findOne, find, create, update and delete there : Core controllers.

# Example

If you've generated an API called Restaurant using the CLI strapi generate:api restaurant or the administration panel, your model looks like this:

Path — ./api/restaurant/models/Restaurant.settings.json

The generated GraphQL type and queries will be:

The queries and mutations will use the generated controller's actions as resolvers. It means that the restaurants query will execute the Restaurant.find action, the restaurant query will use the Restaurant.findOne action and the createRestaurant mutation will use the Restaurant.create action, etc.

# Aggregation & Grouping

✋ CAUTION

This feature is only available on Mongoose ORM.

Strapi now supports Aggregation & Grouping.Let's consider again the model mentioned above:

Strapi will generate automatically for you the following queries & types:

# Aggregation

Getting the total count and the average likes of restaurants:

Query

Let's say we want to do the same query but for only open restaurants

Query

Getting the average likes of open and non open restaurants

Query

Response

(Video) CRUD Operations with the Strapi GraphQL API

# Customize the GraphQL schema

If you want to define a new scalar, input or enum types, this section is for you. To do so, you will have to create a schema.graphql.js file. This file has to be placed into the config folder of each API ./api/*/config/schema.graphql.js or plugin ./extensions/*/config/schema.graphql.js.

Structure — schema.graphql.js.

  • definition (string): lets you define new type, input, etc.
  • query (string): where you add custom query.
  • mutation (string): where you add custom mutation.
  • type (object): allows you to add description, deprecated field or disable the Shadow CRUD feature on a specific type.
  • resolver (object):
    • Query (object): lets you define custom resolver, policies for a query.
    • Mutation (object): lets you define custom resolver, policies for a mutation.

# Example

Let say we are using the same previous Restaurant model.

Path — ./api/restaurant/config/schema.graphql.js

# Define a new type

Edit the definition attribute in one of the schema.graphql.js files of your project by using the GraphQL Type language string.

💡 TIP

The easiest way is to create a new model using the CLI strapi generate:model category --api restaurant, so you don't need to customize anything.

To explore the data of the new type Person, you need to define a query and associate a resolver to this query.

💡 TIP

The resolver parameter also accepts an object as a value to target a controller located in a plugin.

# Add description and deprecated reason

One of the most powerful features of GraphQL is the auto-documentation of the schema. The GraphQL plugin allows you to add a description to a type, a field and a query. You can also deprecate a field or a query.

Path — ./api/restaurant/models/Restaurant.settings.json

It might happen that you want to add a description to a query or deprecate it. To do that, you need to use the schema.graphql.js file.

✋ CAUTION

The schema.graphql.js file has to be placed into the config folder of each API ./api/*/config/schema.graphql.js or plugin ./extensions/*/config/schema.graphql.js.

Path — ./api/restaurant/config/schema.graphql.js

# Execute a policy before a resolver

Sometimes a query needs to be only accessible to authenticated user. To handle this, Strapi provides a solid policy system. A policy is a function executed before the final action (the resolver). You can define an array of policy that will be executed in order.

In this example, the policy isAuthenticated located in the users-permissions plugin will be executed first. Then, the isOwner policy located in the Restaurant API ./api/restaurant/config/policies/isOwner.js. Next, it will execute the logging policy located in ./config/policies/logging.js. Finally, the resolver will be executed.

(Video) Strapi GraphQL - Login & Authenticated CRUD Operations

💡 TIP

There is no custom resolver in that case, so it will execute the default resolver (Restaurant.find) provided by the Shadow CRUD feature.

# Link a query or mutation to a controller action

By default, the plugin will execute the actions located in the controllers that have been generated via the Content-type Builder plugin or the CLI. For example, the query restaurants is going to execute the logic inside the find action in the Restaurant.js controller. It might happen that you want to execute another action or a custom logic for one of your queries.

In this example, it will execute the findByChef action of the Restaurant controller. It also means that the resolver will apply on the restaurants query the permissions defined on the findByChef action (through the administration panel).

💡 TIP

The obj parameter is available via ctx.params and the options are available via ctx.query in the controller's action.

The same process is also applied for the createRestaurant mutation. It will execute the customCreate action of the Restaurant controller.

💡 TIP

The where parameter is available via ctx.params and the data are available via ctx.request.body in the controller's action.

# Define a custom resolver

You can also execute a custom logic like above. However, the roles and permissions layers won't work.

# Apply permissions on a query

It might happen that you want to apply our permissions layer on a query. That's why, we created the resolverOf attribute. This attribute defines which are the permissions that should be applied to this resolver. By targeting an action it means that you're able to edit permissions for this resolver directly from the administration panel.

# Disable a query or a type

To do that, we need to use the schema.graphql.js like below:

# Disable a type attribute

To do that, we need to use the schema.graphql.js like below:

# FAQ

How are the types name defined?

The type name is the global ID of the model. You can find the global ID of a model like that strapi.models[xxx].globalId or strapi.plugins[xxx].models[yyy].globalId.

Where should I put the field description and deprecated reason?

We recommend putting the field description and deprecated reason in the model. Right now, the GraphQL plugin is the only which uses these fields. Another plugin could use this description in the future as well. However, sometimes you don't have the choice, especially when you're defining a custom type.

✏️ NOTE

It's not a bad practice to put the description and deprecated attribute in the schema.graphql.js, though.

Why are the "createdAt" and "updatedAt" field added to my type?

The plugin detects if the timestamps option is set to true in the model. By default, when you generate an API this option is checked. Set it to false in your model to remove these fields.

(Video) Strapi crash course: build a full application with Strapi 4

FAQs

Does Strapi support GraphQL? ›

Strapi provides a programmatic API to customize GraphQL, which allows: disabling some operations for the Shadow CRUD.

How do you count in GraphQL? ›

# Count with GraphQL
  1. Setup the application. In this example, we will use a Restaurant API. Make sure you have a Content Type with some entries.
  2. Create schema. graphql file. ...
  3. Create count query. The count query will call the count service function of the Restaurant API. ...
  4. Query example. Count all restaurants.

Is Strapi a REST API? ›

The REST API allows accessing the content-types through API endpoints. Strapi automatically creates API endpoints when a content-type is created. API parameters can be used when querying API endpoints to refine the results.

Is Strapi self hosted? ›

Strapi is self-hosted. It's up to you to decide where to deploy and host your Strapi project. We have a list of deployment guides for Amazon AWS, Microsoft Azure, DigitalOcean, Google App Engine and Heroku.

What are some differences between rest and GraphQL? ›

GraphQL is an application layer server-side technology that is used for executing queries with existing data, while REST is a software architectural style that defines a set of constraints for creating Web services. GraphQL can be organized in terms of a schema, whereas REST can be arranged in terms of endpoints.

What is Strapi used for? ›

Strapi is a headless CMS that is used to develop websites, mobile applications, eCommerce sites, and APIs. It allows you to create an API without knowing anything about the backend or databases. The system builds APIs based on content models automatically, making it easy to view data in the CMS with Strapi examples.

How do you populate a Strapi? ›

Complex populating can be achieved by using the filters parameter and select or populate nested relations or components: const entries = await strapi. entityService.

What is dynamic zone in Strapi? ›

Dynamic Zones is a new native feature in Strapi that lets teams build reusable content models and minimize the number of changes developers need to make to add new content.

How does GraphQL fetch data? ›

In GraphQL, you fetch data with the help of queries. A query is a GraphQL Operation that allows you to retrieve specific data from the server. We ask the server for all the todos and their titles in the above query. The “ todos " represents an object and " title " a field.

How do you query data in GraphQL? ›

Let us create a simple application to understand the query variable.
  1. Step 1 − Edit Schema File. Add a sayHello field which takes a string parameter and returns a string. ...
  2. Step 2 − Edit resolver. js File. ...
  3. Step 3 − Declare Query Variable in GraphiQL. A variable is declared with $ followed by name of the variable.

How do you limit a query in GraphQL? ›

GraphQL Query Depth Limiting with Express - YouTube

Is Strapi a backend? ›

Strapi runs an HTTP server based on Koa , a back end JavaScript framework.

Is Strapi any good? ›

Strapi has an overall rating of 4.7 out of 5 stars based on 48 user reviews on Capterra.

Is Strapi a headless CMS? ›

Strapi is an open-source, Node. js based, Headless CMS that saves developers a lot of development time while giving them the freedom to use their favorite tools and frameworks.

What language does Strapi use? ›

Python is a programming language that lets you work quickly and integrate systems more effectively. Manage your Python application content with a powerful headless CMS. Open Source, customizable, and self-hosted, Strapi provides an intuitive admin panel as well as an API consumable from any http client.

Is Strapi better than WordPress? ›

Strapi has 48 reviews and a rating of 4.67 / 5 stars vs WordPress which has 14037 reviews and a rating of 4.56 / 5 stars. Compare the similarities and differences between software options with real user reviews focused on features, ease of use, customer service, and value for money.

Is Strapi free for commercial use? ›

Strapi is open-source and free to use. Added features available with the Enterprise Edition.

Is GraphQL frontend or backend? ›

GraphQL is neither the frontend or backend but rather the language spoken between the two to exchange information.

Is GraphQL Faster Than REST API? ›

GraphQL performance is fast and Rest are multiple network calls take up more time. GraphQL development speed is rapid and Rest are slower.

Is GraphQL difficult to learn? ›

A well-designed API is very easy to use and learn. It's also intuitive, a good point to keep in mind when you're starting to design your API. To solve these problems, Facebook created GraphQL.

Is Strapi a framework? ›

Now, Strapi is an open-source headless CMS that gives developers the freedom to choose their favorite tools and frameworks and allows editors to manage and distribute their content using their application's admin panel.

Can I use Strapi for free? ›

Strapi will always be an open-source and free project.

How is Strapi built? ›

Strapi is built on NodeJS. It internally uses KoaJS as its framework which is developed by the team who created ExpressJS, marketed as 'Next generation web framework'. It works with almost all major databases.

How do you query data on Strapi? ›

You can just call strapi. query('modelName', 'pluginName') to access the query API for any model. These queries handle for you specific Strapi features like components , dynamic zones , filters and search .

What are Strapi components? ›

Components are reusable structures you can share between all your content types. Components can be included in any content type either as a single entry or a list of entries for meta information, links, sections list or any repeatable content.

How do you test API Strapi? ›

Testing the Strapi instance

js . Open the file and paste the code below. const fs = require('fs'); const { setupStrapi } = require('./helpers/strapi'); const chai = require('chai'); const expect = chai.

What is middleware in Strapi? ›

The middlewares are functions which are composed and executed in a stack-like manner upon request. If you are not familiar with the middleware stack in Koa, we highly recommend you to read the Koa's documentation introduction . Enable the middleware in environments settings. Path — config/environments/middleware.

What is single type in Strapi? ›

Single types are content-types that can only manage one entry. Components are a data structure that can be used in multiple collection types and single types.

How do you make a table Strapi? ›

In Strapi, we can create tables by adding a Content Type. So let's dive in and create one for our Painter table. Click on Content Type Builder in the left-side menu and under Content Types click on Create new content type. Enter Painter under Display name and click Continue.

Does Facebook use GraphQL? ›

Facebook experiences these problems with REST and hence built the GraphQL. GraphQL is a declarative way of specifying the data requirements on the client-side. It can be operated on a single end-point. It is more structured than REST.

Is GraphQL a REST API? ›

The core difference between GraphQL and REST APIs is that GraphQL is a specification, a query language, while REST is an architectural concept for network-based software. Note: This article is mostly server-side related. GraphQL is gaining momentum as a successor to REST APIs.

How do you call API in GraphQL? ›

To use the explorer, we'll head to studio.apollographql.com/dev and create an account (using either GitHub or your email). Finally, choose a name for your graph, select the “Development” graph type, add your localhost endpoint (Apollo Server's default is http://localhost:4000), and click “Create Graph”. And that's it!

Is GraphQL SQL or NoSQL? ›

GraphQL is a flexible query language that uses a type system to efficiently return data with dynamic queries. SQL(structured query language) is an older, more adopted language standard used specifically for tabular/relational database systems. Consider GraphQL if you want your API to be built on a NoSQL database.

Does GraphQL use HTTP? ›

HTTP. GraphQL is typically served over HTTP via a single endpoint which expresses the full set of capabilities of the service. This is in contrast to REST APIs which expose a suite of URLs each of which expose a single resource.

Is GraphQL a language or a framework? ›

GraphQL is a query language and server-side runtime for application programming interfaces (APIs) that prioritizes giving clients exactly the data they request and no more. GraphQL is designed to make APIs fast, flexible, and developer-friendly.

Are there any disadvantages to GraphQL? ›

Disadvantages of GraphQL

It is just a simple query language. When a query is requested, the server performs database access. When we have to access multiple fields in one query whether it is requested in a RESTful architecture or GraphQL, the varied resources and fields still have to be retrieved from a data source.

What is GraphQL query complexity? ›

The complexity calculation of a GraphQL query can be customized with so called complexity estimators. A complexity estimator is a simple function that calculates the complexity for a field. You can add any number of complexity estimators to the rule, which are then executed one after another.

How do you use middleware in GraphQL? ›

To use middleware with a GraphQL resolver, just use the middleware like you would with a normal Express app. The request object is then available as the second argument in any resolver.

Is NoSQL a Strapi? ›

Strapi supports both NoSQL and SQL databases. Changing the database is as simple as changing the env variable in the configuration folder. By default, Strapi uses SQLite, which is good for local testing, but in production you should use a production-ready database such as PostgreSQL or MySQL.

Is Strapi TypeScript? ›

Strapi supports TypeScript in new projects on v4. 3.0 and above. Existing JavaScript projects can add TypeScript support through a conversion procedure. TypeScript-enabled projects allow developing plugins with TypeScript as well as using TypeScript typings.

Is Strapi open-source? ›

Strapi - Open source Node.js Headless CMS 🚀

What are the limitations of Strapi? ›

Strapi is not an exception, and it also has some disadvantages:
  • Migrating Existing APIs is Not Straightforward. ...
  • Limited TypeScript Support. ...
  • Strapi is not fully open source. ...
  • Frequent Updates.
26 Nov 2021

Who uses Strapi CMS? ›

Thousands of companies and enterprises such as Societe Generale, IBM, Discovery Channel, and ASOS are already using Strapi to build and manage their blogs, editorial, corporate or catalog websites and mobile applications.

How does a headless CMS work? ›

A headless CMS is a content management system that separates where content is stored (the “body”) from where it is presented (the “head“). You can store the content in your headless CMS and then send it to display anywhere – offering a lot more flexibility as to how it's presented in different places.

Which database does Strapi use? ›

By default, Strapi uses the SQLite for content storage, but Strapi is not only limited to using SQLite as the database. It can be configured to use other databases like MySQL, MariaDB, PostgreSQL, etc.

Does Strapi support MongoDB? ›

Strapi v4 does not support MongoDB databases (see blog post announcement ).

Are Strapi CMS good? ›

Strapi offers great flexibility and very granular (low-level) modeling of APIs, which may be created by this software. It has some drawbacks when it comes to migrating data and structure from classic CMSs (like WordPress). In most cases, a headless CMS requires a dedicated solution (so additional code development).

What is Strapi used for? ›

Strapi is a headless CMS that is used to develop websites, mobile applications, eCommerce sites, and APIs. It allows you to create an API without knowing anything about the backend or databases. The system builds APIs based on content models automatically, making it easy to view data in the CMS with Strapi examples.

What is GraphQL in Gatsby? ›

When building with Gatsby, you access your data through a query language named GraphQL. GraphQL allows you to declaratively express your data needs. This is done with queries , queries are the representation of the data you need.

How do you populate a Strapi? ›

Complex populating can be achieved by using the filters parameter and select or populate nested relations or components: const entries = await strapi. entityService.

What is dynamic zone in Strapi? ›

Dynamic Zones is a new native feature in Strapi that lets teams build reusable content models and minimize the number of changes developers need to make to add new content.

Can Strapi be used as a backend? ›

Strapi is a headless CMS that allows you to easily build customizable backend services.

What language does Strapi use? ›

Python is a programming language that lets you work quickly and integrate systems more effectively. Manage your Python application content with a powerful headless CMS. Open Source, customizable, and self-hosted, Strapi provides an intuitive admin panel as well as an API consumable from any http client.

Is Strapi better than WordPress? ›

Strapi has 48 reviews and a rating of 4.67 / 5 stars vs WordPress which has 14037 reviews and a rating of 4.56 / 5 stars. Compare the similarities and differences between software options with real user reviews focused on features, ease of use, customer service, and value for money.

Can I use Gatsby without GraphQL? ›

It's also possible to use an “unstructured data” approach in Gatsby sites, no GraphQL required. Note: For our purposes here, “unstructured data” means data “handled outside of Gatsby's data layer” (we're using the data directly, and not transforming the data into Gatsby nodes).

What are root fields in GraphQL? ›

Root fields & resolvers

At the top level of every GraphQL server is a type that represents all of the possible entry points into the GraphQL API, it's often called the Root type or the Query type. In this example, our Query type provides a field called human which accepts the argument id .

How does Strapi connect to Gatsby? ›

  1. Install Strapi on your machine or launch an instance with a One-Click deploy button.
  2. Add our Strapi source plugin to your Gatsby application including minimal configurations.
  3. Access all your Strapi data using GraphQL queries.

How do you query data on Strapi? ›

You can just call strapi. query('modelName', 'pluginName') to access the query API for any model. These queries handle for you specific Strapi features like components , dynamic zones , filters and search .

What are Strapi components? ›

Components are reusable structures you can share between all your content types. Components can be included in any content type either as a single entry or a list of entries for meta information, links, sections list or any repeatable content.

How do you test API Strapi? ›

Testing the Strapi instance

js . Open the file and paste the code below. const fs = require('fs'); const { setupStrapi } = require('./helpers/strapi'); const chai = require('chai'); const expect = chai.

What is middleware in Strapi? ›

The middlewares are functions which are composed and executed in a stack-like manner upon request. If you are not familiar with the middleware stack in Koa, we highly recommend you to read the Koa's documentation introduction . Enable the middleware in environments settings. Path — config/environments/middleware.

What is single type in Strapi? ›

Single types are content-types that can only manage one entry. Components are a data structure that can be used in multiple collection types and single types.

How do you make a table Strapi? ›

In Strapi, we can create tables by adding a Content Type. So let's dive in and create one for our Painter table. Click on Content Type Builder in the left-side menu and under Content Types click on Create new content type. Enter Painter under Display name and click Continue.

Videos

1. Trying to Upload File to Strapi using GraphQL API - Kevin - 1-on-1 Meeting
(Lovia Team)
2. Strapi Headless CMS - GraphQL API CRUD operation (Create) Part 1
(Lovia Team)
3. Let's Learn Nuxt and Strapi
(Debbie O'Brien)
4. Strapi v3 to v4 Migration Overview [ Strapi Migration Guide Part 1 ]
(Strapi)
5. Connecting Your Next App to Strapi with GraphQL
(Strapi)
6. How to use internationalization in Strapi v3
(Strapi)
Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated: 02/05/2023

Views: 5801

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.