Laravel & LumenRESTFulAPI extension package: DingoAPI (3) -- Response (Response)

Source: Internet
Author: User
Laravel & LumenRESTFulAPI extension package: DingoAPI (III) -- Response (Response) the function of an API is to obtain the request and return the Response to the client. the Response format is diverse, such as JSON, the response methods are also diverse, depending on the complexity of the currently built API and future considerations.

The simplest way to return a response is to directly return an array or object from the controller, but not every response object can ensure correct format, therefore, make sure that they implement the ArrayObject or Illuminate \ Support \ Contracts \ ArrayableInterface interface:

class UserController{    public function index()    {        return User::all();    }}

In this example, the User class inherits from Illuminate \ Database \ Eloquent \ Model, which means that the returned data can be formatted as an array. of course, you can also return a single User:

class UserController{    public function show($id)    {        return User::findOrFail($id);    }}

The Dingo API will automatically format the response in JSON format and set the Content-Type header to application/json.

1. response builder

The response builder provides a smooth interface for us to easily build more custom responses. The response builder is usually used with the Transformer.

To use the response builder Controller, you need to use Dingo \ Api \ Routing \ Helperstrait. to enable each Controller to use this trait, we place it in the API Base Controller:

use Dingo\Api\Routing\Helpers;use Illuminate\Routing\Controller;class BaseController extends Controller{    use Helpers;}

Now you can define a controller that inherits from the controller. in these controllers, you can access the response builder through the $ response attribute.

Array response
class UserController extends BaseController{    public function show($id)    {        $user = User::findOrFail($id);        return $this->response->array($user->toArray());    }}
Single Item response
class UserController extends BaseController{    public function show($id)    {        $user = User::findOrFail($id);        return $this->response->item($user, new UserTransformer);    }}
Set response
class UserController extends BaseController{    public function index()    {        $users = User::all();        return $this->response->collection($users, new UserTransformer);    }}
Paging response
class UserController extends BaseController{    public function index()    {        $users = User::paginate(25);        return $this->response->paginator($users, new UserTransformer);    }}
No content response
return $this->response->noContent();
Create response
return $this->response->created();

You can also use location information as the first parameter for creating resources:

return $this->response->created($location);
Error response

You can use multiple built-in errors to generate error responses:

// A generic error with custom message and status code.return $this->response->error('This is an error.', 404);// A not found error with an optional message as the first parameter.return $this->response->errorNotFound();// A bad request error with an optional message as the first parameter.return $this->response->errorBadRequest();// A forbidden error with an optional message as the first parameter.return $this->response->errorForbidden();// An internal error with an optional message as the first parameter.return $this->response->errorInternal();// An unauthorized error with an optional message as the first parameter.return $this->response->errorUnauthorized();
Add additional response headers

After using the preceding method, you can add a response header to customize the response:

return $this->response->item($user, new UserTransformer)->withHeader('X-Foo', 'Bar');
Add metadata

Some conversion layers may use metadata, which is useful when you need to provide additional data associated with resources:

return $this->response->item($user, new UserTransformer)->addMeta('foo', 'bar');

You can also set a metadata array to replace multiple call methods:

return $this->response->item($user, new UserTransformer)->setMeta($meta);
Set the response status code
return $this->response->item($user, new UserTransformer)->setStatusCode(200);
2. Custom response format

In the installation configuration, we have already touched on the response format. by default, Dingo API automatically uses the JSON format and sets the corresponding Content-Type header. In addition to JSON, there is also a JSONP format, which encapsulates the response into a callback. To register and modify the format, simply replace the default JSON format in the configuration file (Laravel) or startup file (Lumen) with JSONP:

'formats' => [    'json' => 'Dingo\Api\Http\Response\Format\Jsonp']

Or:

Dingo\Api\Http\Response::addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp);

The default query string of the callback parameter is callback by default, which can be set by modifying the first parameter of the constructor. If the query string does not contain any parameters, a JSON response is returned.

You can also register and use the Response Format you need. the custom Format object must inherit from the Dingo \ Api \ Http \ Response \ Format class and implement the following methods: formatEloquentModel, formatEloquentCollection, formatArray, and getContentType.

3. Morphing and Morphed events

Before the Dingo API sends a response, it will first convert the response (morph). This process includes running all Transformer and sending the response in the configured response format. If you need to control how the response is converted, you can use ResponseWasMorphed and ResponseIsMorphing events.

We create a listener for the event in app/Listeners:

use Dingo\Api\Event\ResponseWasMorphed;class AddPaginationLinksToResponse{    public function handle(ResponseWasMorphed $event)    {        if (isset($event->content['meta']['pagination'])) {            $links = $event->content['meta']['pagination']['links'];            $event->response->headers->set(                'link',                sprintf('<%s>; rel="next", <%s>; rel="prev"', $links['links']['next'], $links['links']['previous'])            );        }    }}

Then, you can register an event and its corresponding listener in EventServiceProvider to listen to the event:

protected $listen = [    'Dingo\Api\Event\ResponseWasMorphed' => [        'App\Listeners\AddPaginationLinksToResponse'    ]];

Now, all the responses that contain paging links also add these links to the Link header.

Note: This function is currently in the development stage and is not recommended for production environments.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.