Fourth: Dingo/api latest version of V2.0 responses (serial)

Source: Internet
Author: User

For some reason, can't update on time, alas. I will try my best to speed up. (This sentence is not a translation of the HA)

Original Address--https://github.com/dingo/api/wiki/Responses

A functioning API is built upon receiving requests and returning a consumable response to the client. An API would generally return responses in a easy to consume format such as JSON. There ' s a number of different ways to return responses and it'll largely depend on how complex your API is or would becom E.

One running API is to get the request and return the response information to the client. An API typically returns a response in an easy-to-use format, such as JSON. This is a different way to go back to the request. There are many different ways to return a response, largely depending on the complexity of your API or the future direction of the API.

The easiest-to-return a consumable response is-simply return an array or object directly from your controller. Not every object can is correctly formatted though so you should ensure that it implements either the ArrayObject or the Illuminate\Support\Contracts\ArrayableInterface i Nterface.

The simplest way to return an available response is to return an array or an object directly from the controller. Not every object can be returned in the correct format, but therefore, you should be sure that it inherits the Arrayobject or Illuminate\support\contracts\arrayableinterface interface.

class usercontroller{    publicfunction  index ()    {        return User: : all();    }}

In this example, our user class inherits Illuminate\database\eloquent\model, which means that it can be returned as a formatted array, so we can simply return a users collection by calling User::all ().

Similarly, you can also use it to return a single user. Example: The following

class usercontroller{    publicfunction Show ($id)    {        return user::findorfail ($id);    }}

This package will automatically format the response message after it is returned as a JSON format, and set the Content-type header to Application/json.

Response Builder Response Builder

This response builder provides a smooth interface to simply generate a custom response message. This response builder is typically used in conjunction with Transformers.

To be in your controller, use this response to return. You should introduce (use) dingo\api\routing\helpers. In order for all of your controllers to be able to use this feature, you should create a base class controller that will allow all your controllers to inherit (extends) it.

 Use dingo\api\routing\helpers;  Use Illuminate\routing\controller; class extends controller{    use  Helpers;}

Now, your controller can simply inherit the base controller. In your controller, you can $response access the Response builder via properties.

For more detailed documentation on this, you should look at the Transformers section. (Next, I will slowly translate, etc...) )

Responding with an array returned as an array
class extends basecontroller{    publicfunction Show ($id)    {        $user = User::findorfail ($id);         return $this->response->array($user-ToArray ());}    }   

Responding with a single item returns as an item

class extends basecontroller{    publicfunction Show ($id)    {        $user = User::findorfail ($id);         return $this->response->item ($usernew  usertransformer);}    }
Responding with a Collection of Items returned as a collection of elements
Class Usercontroller extends Basecontroller{public function index () {$users = User::all (); return $this->response- >collection ($users, New Usertransformer);}}

  

Responding with paginated Items return an array with pagination
class extends basecontroller{    publicfunction  index ()    {        $users = User:: Paginate (+);         return $this->response->paginator ($usersnew  usertransformer);}    }
Responding with no content response
return $this->response->nocontent ();
Responding with Created Response creates a response to a resource
return $this->response->created ();

You can also provide a value for this created as the first parameter.

return $this->response->created ($location);
Responding with an error returns a false hint

There are many different responses to the error in this package, and you can quickly form an error prompt. (This piece of text understands, I feel not very good, put the real return value to write out)

return $this->response->error (' This was an error. ', 404);
Return information: {"message": "This is an error.", "Status_code": 404}

return $this->response->errornotfound ();


return $this->response->errorbadrequest ();
Return information: {"message": "Bad Request", "Status_code": 400}

return $this->response->errorforbidden ();

Return information: {"message": "Forbidden", "Status_code": 403}

return $this->response->errorinternal ();

Return information: {"message": "Internal Error", "Status_code": 500}

return $this->response->errorunauthorized ();

Return information: {"message": "Unauthorized", "Status_code": 401}

Adding Additional Headers Add additional header

Once you have used one of these methods, you can further customize the response by adding additional headers.

return $this->response->item ($usernew Usertransformer)->withheader (' X-foo ', ' Bar ');
Adding Meta Data Add metadata

Some conversion tiers may use metadata (meta data). This is useful when you need to provide additional data related to the resource.

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

You can also set an array of meta data to save multiple calls to the Addmeta method.

return $this->response->item ($user, New Usertransformer)->setmeta ($meta);
Setting Response Status Code setting return value state
return $this->response->item ($user, New Usertransformer)->setstatuscode (200);

    

Custom Response Formats Customized response format

In this configuration section, we briefly explain the return information format. With this dingo package, we will automatically use the JSON format and set an appropriate Content-type header. In addition to JSON formatting, there is also a JSONP format. This formatter will respond with a callback package. Changing the format requires simply replacing 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

New DINGO\API\HTTP\RESPONSE\FORMAT\JSONP);

You can register and use the format you need. Your format should inherit the Dingo\api\http\response\format\format. There are many requests that should be defined: Formateloquentmodel,formateloquentcollection,formatarray and getContentType.

Morphing and morphed Events

Before sending a response, it will change it in the send. This process involves running all converters (Transformer) and sending responses in the configured response format. If you need more control over the changes in response, you can use ResponseWasMorphed ResponseIsMorphing both events.

In your App/listeners folder, create a listener.

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 '])}}

The event is then EventServiceProvider monitored by registering the event and its corresponding listener in:

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

Now all responses that contain pagination links would also add these links to the Link header. ( This sentence, left for you to translate)

This chapter is over, it's going to be 2018 years now. New year, go Go go!!!

Fourth: Dingo/api latest version of V2.0 responses (serial)

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.