logo
podcast Podcast
get help Get Unstuck

API resources behave differently if you have a data property

This had me confused for a bit

Joel Clermont
Joel Clermont
2024-09-12

It's been over a year that I've written this daily newsletter. One of the things this practice has changed in me is my attitude when I get a little stumped on a coding issue.

Instead of just being mad, I now see the silver lining of "Hey, I can share this as a tip!"

For example, last week I was working on an API, and I noticed that one specific resource had a different structure than all the rest.

Laravel follows the JSON API recommendations for how to structure the JSON payloads.

Resources are wrapped in a data property, which makes it easy to differentiate resource data from errors and other metadata.

This one API endpoint was not getting wrapped in that property, though, and it was driving me nuts.

I ended up having to step-debug through the request, and I found that if there is already a property called data in my resource definition, Laravel will skip wrapping it in a top-level data property.

I could have forcibly wrapped it myself inside the resource, but in this case, I just decided to rename that data key to something else to avoid the collision.

Here to help,

Joel

P.S. Would you like some help introducing an API specification to your Laravel app? We can get your team started on the right foot.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.