If your service supports all CRUD operations, it is always recommended that you implement the RESTful interface. It's not hard. I have outlined some of the basics below.
The RESTful service simply does a few things:
- It uses the HTTP request method to communicate the CRUD action.
- It uses an HTTP status code to convey the response status and
- It uses a URI to determine your resource (file, database item that you are accessing, etc.).
- He is stateless
The idea is to minimize the development of custom messages for these things that are already defined in the HTTP specification.
1 - REQUEST METHOD
4 HTTP request methods that are required to support a RESTful service:
and you can optionally support
You can map them directly to your CRUD actions as follows:
- POST = Create
- GET = Get
- PUT = Update
- DELETE = Delete
- PATCH = Edit (partial update, for example, “change password.” PUT becomes “replacement”)
- HEAD = Header only (resource metadata)
To do this, program your queries correctly using a simple query method router as follows:
switch ($_SERVER["REQUEST_METHOD"]) { case "POST": // Create action break; case "GET": // Retrieve action break; case "PUT": // Update action break; case "DELETE": // Delete action break; }
2 - STATUS CODE You should also use HTTP status codes from your service to transfer status to the client, for example:
- 20x = success
- 30x = redirection
- 40x = communication problems
- 50x = server error
To do this, simply add the response with the appropriate HTTP header, for example:
header("Status: 500 Internal Server Error");
Here you can refer to the full list of implemented HTTP status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
3 - URIs For URIs, RESTful services typically follow a top-down principle for categorical naming, for example
/object_type/id.content_type
Examples:
POST /user PUT /user/1 GET /user/1.json GET /user/1.html
You can implement a very rudimentary RESTful router for the above agreement using Apache with mod_rewrite in the .htaccess file as follows:
RewriteEngine On RewriteRule ^([^\/]+)\/([^\.]+)\.(\w+)$ index.php?object_type=$1&object_id=$2&content_type=$3
Then you will have index.php Find the appropriate object_type and id for the correct routing, for example:
$object = $_GET["object_type"]; $id = (int) $_GET["object_id"]; $content_type = $_GET["content_type"];
4 - SECURITY Simply put, the server does not support "state" for the client. There are no requirements for storing a session or state. Each request represents a complete transaction. That is, if I am GET user / 1, the server will not remember that I did this, and future requests will not depend on previous ones or will not be affected by previous ones.
If you are implementing these standards, congratulations, you have created a RESTful service!