PHP Serving RESTful APIs Editing a Resource - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Serving RESTful APIs Editing a Resource - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, June 21, 2019

PHP Serving RESTful APIs Editing a Resource

PHP Serving RESTful APIs


Editing a Resource

Problem

You want to let people update a resource.

Solution

Accept requests using PUT. Read the POST body. Return success.

For a PUT request to http://api.example.com/v1/jobs/123:

       PUT /v1/jobs/123 HTTP/1.1
       Host: api.example.com
       Content-Type: application/json
       Content-Length: 49

       {
             "position": {
                   "title": "PHP Developer"
             }
       }

Use this PHP code:

       if ($_SERVER["REQUEST_METHOD"] == 'PUT') {
            $body = file_get_contents('php://input');
            switch(strtolower($_SERVER['HTTP_CONTENT_TYPE'])) {
                 case "application/json":
                      $job = json_decode($body);
                      break;
                 case "text/xml":
                      // parsing here
                      break;
            }

            // Validate input

            // Modify the Resource

            $request = explode('/', substr($_SERVER['PATH_INFO'], 1));
            $resource = array_shift($request);
            $id = update($job, $request[0]); // Uses id from request

            http_response_code(204); // No Content
       }

To generate this output:

       HTTP/1.1 204 No Content

Discussion

To update a resource, accept PUT requests. The resource provided in the POST body replaces the current resource. For an explanation of the logic to parse this request.

If the request is successful, return 204 (No Content). You don’t return 201 because the resource already exists. You can return 200, but 204 is preferable when you don’t return an HTTP body. This allows the client to definitely know nothing was lost.

PUT requests are not safe, but they are idempotent because the resource being PUT entirely replaces the current entity. Unfortunately, this means that even updating a one-character typo requires you to transmit the entire resource.

Some sites allow partial updates using PUT. For example, this request keeps the resource as is, except for updating the postal code:

       PUT /v1/jobs/123 HTTP/1.1
       Host: api.example.com
       Content-Type: application/json
       Content-Length: 43

       {
             "location" {
                   "postalCode": 94043
             }
       }

This makes it hard to disambiguate between when you want to delete a field versus intentionally not providing it. The PATCH method is a proposed standard for partial updates, so you can differentiate your behavior based on a PUT or a PATCH.



No comments:

Post a Comment

Post Top Ad