How to query media fields on Strapi v4 with Gatsby?

System Information
  • Strapi Version: v4.0.0
  • Operating System: Windows 10
  • Database: SQLite
  • Node Version: v16.13.1
  • NPM Version: v7.24.0
  • Yarn Version: v1.22.5

I noticed that the GraphQL API structure has changed since v3. However while using v4, I am unable to query the media field I have set on my Single Type.

I have a “Home” Single Type with two media fields:

I cannot see/query it using Gatsby GQL Explorer under strapiHome.data.atrributes:

is there a reason I’m not seeing the image fields here like I would in v3?

Hi @ChrisLau90
I’m not too deep into GQL with Strapi but maybe you can adapt from this REST API information:
Media, as well as relations, components, and dynamic zones are not getting populated by default in V4 (where they did in V3).

Docs: Population for REST API - Strapi Developer Docs

For the REST API you need to adjust the endpoint (eg. ?populate=*). Or setting up a custom middleware function in the content-type’s route.js file.

EDIT: does the example code her help? GraphQL API - Strapi Developer Docs

Hopefully this helps.

Hi @mrt-stl , thanks for your response.

I am confused as to what this means in terms of my Gatsby project, as the API URL is set in the gatsby-config file like so:

{
      resolve: "gatsby-source-strapi",
      options: {
        apiURL: process.env.API_URL || "http://localhost:1339/api",
        collectionTypes: ["tag", "peace-brief", "focus-group"],
        singleTypes: ["homepage", "global"],
        queryLimit: 1000,
      },
    }

does that mean the apiURL should be something like http://localhost:1339/api?populate=headerImage? I don’t understand what to put after ?populate=

Thanks again

For relational data such as Media, which contains more information than one field, you will need to drill down with the GraphQL Query. e.g.

data{
     attributes{
         headerImage{
              data{
                    attributes{
                         formats
                     }
               }
         }
    }
}

Hi there,

Experienced the same issue with nested collectionTypes.

For Rest API, the solution is indeed to use ?populate=*

For GraphQL the solution is to add this to your gatsby-config:
{
name: ‘article’,
endpoint: ‘api/articles’,
api: {qs: {populate: ‘*’}}
}

After this, restart your server and it should work.

Let me know.

Kind regards, Jeroen

Hi, @ChrisLau90
How are you doing?

I’ve encountered the same issue as you.
Could you let me know wether you solve this problem?

Hi, @Jeroen_Swart

If possible could you show me the gatsby-config.js file?

Thanks