7

I have a problem where none of the relational fields are present in the responses after fetching my data. When I look to the schema of one of my schemas with a relation, I see that the relational fields are present in the attributes object. But still I only get the non-relational fields in my response.

This is one of my schemas

{
  "kind": "collectionType",
  "collectionName": "activities",
  "info": {
    "singularName": "activity",
    "pluralName": "activities",
    "displayName": "activity"
  },
  "options": {
    "draftAndPublish": true
  },
  "pluginOptions": {},
  "attributes": {
    "name": {
      "type": "string"
    },
    "date": {
      "type": "date"
    },
    "subcategory": {
      "type": "relation",
      "relation": "oneToOne",
      "target": "api::subcategory.subcategory"
    },
    "members": {
      "type": "relation",
      "relation": "manyToMany",
      "target": "api::member.member",
      "inversedBy": "activities"
    }
  }
}
Talha Bayansar
  • 105
  • 1
  • 6

1 Answers1

34

In Strapi v4 relations are not populated when fetching entries by default.

Explaination:

Queries can accept a populate parameter to explicitly define which fields to populate, with the following syntax:

GET /api/:pluralApiId?populate=field1,field2

Example request: Get books and populate relations with the author's name and address

GET /api/books?populate=author.name,author.address

For convenience, the * wildcard can be used to populate all first-level relations:

Example request: Get all books and populate all their first-level relations

GET /api/books?populate=*

Example request: Get all books and populate with authors and all their relations

GET /api/books?populate[author]=*

Note: Only first-level relations are populated with populate=*. Use the LHS bracket syntax (i.e. [populate]=*) to populate deeper:

Example request: Get all relations nested inside a "navigation" component in the "global" single type

GET /api/global?populate[navigation][populate]=*

Solution:

Change your API url to one of the following and you should be able to see the related fields populated in the response.

GET /api/activities?populate=subcategory,members

OR

GET /api/activities?populate=*

Reference:

dulange
  • 281
  • 3
  • 16
Salvino D'sa
  • 4,018
  • 1
  • 7
  • 19
  • 2
    ıt's very clear and good answer. Thanks ! – Ugur Sep 24 '22 at 17:53
  • 2
    Important thing when Relation used is of type plugin `Users-Permissions` Under admin panel, for Public access to Roles, `find` access has to be granted explicitly. Otherwise the relation does not appear in response even with `populate=*` More read the Caution section at - https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest/populating-fields.html#population – pjoshi Nov 23 '22 at 03:40