Syndra is a Laravel package. It provides you with predefined JSON responses to use in your API.
When building an API you have to standardize it so that you can always expect the same response for similar requests.
When using resource controllers these methods usually are: index
, store
, update
, destroy
.
For the index
method you want to output data. That can be achieved with Syndra::respond($data)
. By default the status code is 200, but you can change it manually using Syndra::setStatusCode($statusCode)->respond($data)
. Syndra goes great with Fractal. To learn how to use them together read Laravel API 101.
Another thing that you will most likely want to do is to enable CORS. This can be achieved by setting the appropriate headers:
return Syndra::setHeaders([
'Access-Control-Allow-Origin' => '*',
])
->setStatusCode($statusCode)
->respond($data);
In the store
method you want to return that the resource was created. Syndra enables you to do this easily with Syndra::respondCreated()
. This generates the following response:
{
"message": "Created",
"status_code": 201
}
You can customize the message by passing the message as a parameter Syndra::respondCreated('The resource has been created!')
.
You can almost guess which method we use for when the resource has been updated by now; Syndra::respondUpdated()
. By default this returns message Updated
with status code 202. As with respondCreated
, you can set the message by passing it as a parameter to respondUpdated
.
For the destroy
method I like to return status code 200 with a message Ok
. This can be done with Syndra::respondOk()
.
By applying what you have learned so far, you can now easily build your API responses however you want and they will be consistent throughout your entire API.
In this chapter I will show you how to handle most common situations which can occur in your application.
If you are using $this->validate($request, $rules)
from your controller to validate data, you would want Syndra to return validation errors if the validation fails. To do that, go to app/Exceptions/Handler.php
and in render
method add this block of code:
if ($e instanceof ValidationException) {
return \Syndra::respondValidationError(
$e->validator->errors()->getMessages()
);
}
If the validation fails, the response will be similar to the one bellow but with different messages:
{
"error" : {
"message": {
"email": [
"The email format is invalid."
]
},
"status_code": 422
}
}
Similar to handling validation errors, model not found errors are addressed in the same way. Go to app/Exceptions/Handler.php
and in render
method add this block of code:
if ($e instanceof ModelNotFoundException) {
return \Syndra::respondNotFound();
}
Now every time you use Model::findOrFail($id)
in your controller and it does not find anything you will get this JSON response:
{
"error" : {
"message": "Not Found",
"status_code": 404
}
}
From your AuthController
, if the authentication attempt fails you can return Syndra::respondUnauthorized()
or if the authenticated user lacks permissions to do something you can return Syndra::respondForbidden()
. Both methods accept message as the first parameter.
Hint! You can even pass an array instead of a string as a message.
In the case that something goes terribly wrong, you can shamefully respond with Syndra::respondInternalError()
.
From the command line:
composer require laravelista/syndra
Include the service provider in config/app.php
:
'providers' => [
...,
Laravelista\Syndra\SyndraServiceProvider::class
];
And add a facade alias to the same file at the bottom:
'aliases' => [
...,
'Syndra' => Laravelista\Syndra\Facades\Syndra::class
];
There are two way of working with Syndra. As a facade Syndra::respond($data)
or as a injected dependency $this->syndra->respond($data)
:
use Laravelista\Syndra\Syndra;
protected $syndra;
public function __construct(Syndra $syndra)
{
$this->syndra = $syndra
}
This is useful for index
and show
method. Use this when you want to return custom JSON output, like the one you get from Fractal.
Syndra::respond(array $data)
Use this for responding with messages. This returns a predefined message JSON template which contains the message and the status code.
Syndra::respondWithMessage($message='Ok')
Response:
{
"message": "Ok",
"status_code": 200
}
Use this for responding with error messages. This returns a predefined error JSON template which contains the message and the status code wrapped in error.
Syndra::respondWithError($message='Error')
Response:
{
"error": {
"message": "Error",
"status_code": 200
}
}
Use this to respond with a message (200).
Syndra::respondOk($message='Ok')
Use this when a resource has been created (201).
Syndra::respondCreated($message='Created')
Use this when a resource has been updated (202).
Syndra::respondUpdated($message='Updated')
Use this when the user needs to be authorized to do something (401).
Syndra::respondUnauthorized($message='Unauthorized')
Use this when the user does not have permission to do something (403).
Syndra::respondForbidden($message='Forbidden')
Use this when a resource is not found (404).
Syndra::respondNotFound($message='Not Found')
Use this when the validation fails (422).
Syndra::respondValidationError($message='Validation Error')
Use this for general server errors (500).
Syndra::respondInternalError($message='Internal Error')
Use this for HTTP not implemented errors (501).
Syndra::respondNotImplemented($message='Not Implemented')
Sets status code manually. This method can be chained (combined) with other methods.
Syndra::setStatusCode($statusCode)
Example:
Syndra::setStatusCode(200)->respond($data);
Sets headers on the response. This method can be chained (combined) with other methods.
Syndra::setHeaders(array $headers)
Example:
Syndra::setHeaders($headers)->respondWithMessage('Hello World!');
Many thanks to:
- @delatbabel for
notImplemented
method and default message values