Laravel & Lumen RESTFul API Expansion pack: Dingo API (three)--Response (response)

Source: Internet
Author: User
The main function of an API is to get the request and return the response to the client, the format of the response is diverse, such as JSON, the way to return the response is also diverse, depending on the complexity of the currently built API and the future considerations.

The simplest way to return a response is to return an array or object directly from the controller, but not every response object is guaranteed to be well-formed, so make sure that they implement Arrayobject or illuminate\support\contracts\ Arrayableinterface Interface:

Class usercontroller{public    function Index ()    {        return User::all ();}    }

In this case, the user class inherits from Illuminate\database\eloquent\model, which means that the returned data can be formatted as an array, and can of course return a single user:

Class Usercontroller{public    function Show ($id)    {        return user::findorfail ($id);}    }

The Dingo API automatically formats the response in JSON format and sets the Content-type header to Application/json.

1. Response Builder

The response builder provides a smooth interface so that we can easily build more customized responses. The response builder is typically used with converters (Transformer).

To use the Response Builder controller requires the use of dingo\api\routing\helperstrait, in order for each controller to be able to use this trait, we place it in the Api base class controller controllers:

Use Dingo\api\routing\helpers;use illuminate\routing\controller;class Basecontroller extends Controller{use    Helpers;}

It is now possible to define a controller that inherits from the controller, where the response builder can be accessed through $response properties.

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); C11/>return $this->response->item ($user, New Usertransformer);}    }

Collection 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::p aginate;        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 to create a resource:

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

Error Response

You can generate error responses using a variety of built-in errors:

A generic error with the custom message and status Code.return $this->response->error (' This was an error. ', 404);//A Not found error with an optional message as the first Parameter.return $this->response->errornotfound ();//A Bad req Uest 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 wit H an optional message as the first Parameter.return $this->response->errorunauthorized ();

add additional response headers

After using the above method, you can also customize the response by adding a response header:

return $this->response->item ($user, New Usertransformer)->withheader (' X-foo ', ' Bar ');

Add Meta Data

Some conversion tiers may use metadata (meta data), which is useful when you need to provide additional data associated with a resource:

return $this->response->item ($user, New Usertransformer)->addmeta (' foo ', ' Bar ');

You can also set the metadata array to replace calls to multiple method chains:

return $this->response->item ($user, New Usertransformer)->setmeta ($meta);

Setting the response status code

return $this->response->item ($user, New Usertransformer)->setstatuscode (200);

2. Custom Response Format

We have simply contacted the response format in the installation configuration, and by default the Dingo API automatically uses the JSON format and sets the corresponding Content-type header. In addition to JSON, there is a JSONP format, which wraps the response into a callback. To register the format, simply replace the default JSON format in the configuration file (Laravel) or the boot file (lumen) with the JSONP:

' Formats ' = [    ' json ' = ' DINGO\API\HTTP\RESPONSE\FORMAT\JSONP ']

Or:

Dingo\api\http\response::addformatter (' JSON ', new DINGO\API\HTTP\RESPONSE\FORMAT\JSONP);

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

You can also register and use the response format you need, and the custom format object needs to inherit from the Dingo\api\http\response\format\format class, along with the following methods: Formateloquentmodel, Formateloquentcollection, Formatarray and getContentType.

3, morphing and morphed events

The response is converted (morph) before the Dingo API sends the response, which includes running all converters (Transformer) and sending the response in the configured response format. If you need to control how responses are converted you can use the responsewasmorphed and responseismorphing events.

We create listeners for events 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 listen for the event by registering the event and its corresponding listener in Eventserviceprovider:

protected $listen = [    ' dingo\api\event\responsewasmorphed ' = [        ' app\listeners\ Addpaginationlinkstoresponse ']    ;

Now all responses that contain paging links will also add these links to the link header.

Note: This feature is currently in development and is not recommended for production environments.

  • Related Article

    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.