APIs
The majority of APIs we build (and interact with) are in the JSON format.
Responses
Eloquent API Resources, Fractal or 🤔
There are various ways and packages which enable you to use a layer to transform/format your data before it is returned via your api - Transformers if you will...
Eloquent - API Resources
Built directly into the core of Laravel, so no external packages are required. Can be used for both simple and complex APIs, does lack some more complex functionality such including nested data.
Documentation – Eloquent: API Resources
Fractal
An external package maintained by The PHP League. Suitable for complex APIs - overkill for small APIs. Does require additional code to be added for instantiation (spatie/laravel-fractal adds this).
GraphQL
🤯
Namespaced Data
Data in responses should be namespaced under a data
key. This allows for additional metadata, such as pagination to be returned alongside the response data.
❌ Incorrect
[
{
"name": "John Doe"
},
{
"name": "Sally Marshall"
}
]
✅ Correct
{
"data": [
{
"name": "John Doe"
},
{
"name": "Sally Marshall"
}
],
"meta": {}
}
Naming of Properties
Properties in responses must be named using snake_case
.