REST API relation types are `string|Type` but always(?) `Type`

default discord avatar
2 months ago

I'm testing out PayloadCMS for our projects. I've noticed that when I do a query for, say, a Post that has a


(relation to another collection type) that the API response is always the Media type and never a


which I assume means its either an


or the object itself.

This feels... not great? Are there best practices to know what I'm getting or asking for one way or another?

According to the types, presumably I'd have to check if each relation is a string or not and then go fetch the asset if it is a string, which seems a bit ridiculous

Is the real recommended method to use GraphQL and some sort of codegen instead of REST?

  • discord user avatar
    Payload Team
    2 months ago

    Yes that is what you need to do if you truly want type safety. A few things are responsible for a string being returned, access control and depth being the most common. If you query a document with the query param


    all relationship fields on the doc will return only the ID. If the user requesting does not have access to the doc, the ID will return.

    Here is a way to type guard, but you would still want to handle cases where only an ID is returned:
  • default discord avatar
    2 months ago

    thank you, i'll look into it

    @jarrod_not_jared I should ask... do you have a recommendation for a package or set of packages to introspect the GraphQL endpoint and generate a type-safe client?

    I've set that up a long time ago for some other project but can't really recall what I used

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!


Connect with the Payload Community on Discord



Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.