📜 ⬆️ ⬇️

RESTful PHP - 5 simple tips

REST (Representational state transfer) is an architectural style or set of conventions for web applications and services, based on the manipulation of resources and the HTTP specification. Roy Fielding, one of the founding fathers of HTTP (Hypertext Transfer Protocol), spoke about this for the first time.

Web applications often ignore the HTTP specification and move forward using favorite features: GET and POST, 200 OK and 404 NOT FOUND. Since programmed web applications are used, with their own APIs, the decision to ignore the HTTP specification can create problems later. As a result, we have many applications with GET and POST interfaces. For example, user delete interface: GET / user / 1 / delete against POST / user / delete {id = 1}; in the case of REST, you can specify / user / 1 is a resource, and deleting HTTP is the DELETE method.

Important HTTP methods such as POST, GET, PUT, and DELETE are often compared to CREATE, READ, UPDATE, DELETE (CRUD) database manipulation operations. HTTP separates the notion of a web server and a web browser. This allows each implementation to be different from other similar, based on the "client / server" principle.

Now it's time to look at the examples, so it will be clearer.
')

1. Using the PUT and DELETE methods


In PHP, you can easily determine the HTTP method used; just refer to the $_SERVER['REQUEST_METHOD']; system array variable $_SERVER['REQUEST_METHOD']; In the case of web browsers, either the GET or the POST method is registered there. REST client applications require PUT, DELETE support and preferably OPTIONS and others . But unfortunately in PHP there is no $ _PUT and $ _DELETE, unlike $ _GET and $ _POST. Here is a way to correct the omission:

 $_PUT = array(); if($_SERVER['REQUEST_METHOD'] == 'PUT') {   $putdata = file_get_contents('php://input');   $exploded = explode('&', $putdata);    foreach($exploded as $pair) {     $item = explode('=', $pair);     if(count($item) == 2) {       $_PUT[urldecode($item[0])] = urldecode($item[1]);     }   } } 


Thus, we have an array of $ _PUT, similar to $ _POST with the exception of superglobalnosti.

2. Sending custom HTTP 1.1 headers


PHP allows customization of headers sent to the client. In turn, the header contains the response code from the server. By default, PHP will respond with 200 OK to a successful request, to use the die () function, or to create a new resource. Actually there are two ways to customize the situation:

 header('HTTP/1.1 404 Not Found'); //  header('Location: http://www.foo.com/bar', true, 201); // 201 CREATED 


The first option is a fairly standard method for setting the response code. If you need to specify a redirection to the resource “201 Created” or “301 Moved Permanently”, this is easy to implement by specifying the code in the third parameter of the function header (), as shown in the example. The second example can be replaced by a more readable code:

 header('HTTP/1.1 201 Created'); header('Location: http://www.foo.com/bar'); 


3. Sending Significant HTTP Headers


The point is to use header specifications that are quite self-contained, but are often ignored or emulated by more stereotyped decisions.

201 Created - used if a new resource has been created. It should be used with the functionality of referral to the resource, for example / tech / news, because he does not use automatic directions.

202 Accepted - as if telling the customer "your order has been accepted and will be processed soon." Unlike code 201, which is sent after creating a resource, code 202 queues the request.

204 No Content - In conjunction with caching and conditional GET request (requests with If-Modified-Since / If-None-Match headers), allows web applications to say "the content has not changed, continue to use the cached version", without re-processing and sending cache.

401 Unauthorized - should be used when trying to access a resource that requires a certain level of access. Used in conjunction with www-authentication.

500 Internal Server Error - much better than 200 OK, when the PHP script is no longer breathing or has led to an exception.

Naturally, there are many more titles; on this topic it has been repeatedly written, the ones listed above are just examples.

4. Do not use $ _SESSION


A real RESTful PHP application should be completely independent; all requests should contain enough information so that they can be responded to without any additional effort from the server. In practice, this implies the preservation of authorization information in cookies with a date (timestamp) and a checksum. Additional information can also be stored in cookies. If you need to save large amounts of data, you can put them in a database, authorization information should be left in the cookies. UPD: It is necessary to make a reservation that the use of cookies does not fully comply with the REST ideology, since session communications are saved. But in the case of cookies, session information is stored on the client, and in the case of session, session connections are stored in the server’s temporary directory and in the client’s session cookie (if “session.use_cookies” is enabled).

5. Testing with cURL or rest-client


cURL makes it easy to execute any HTTP methods for the desired resource. You can send any request parameters and headers, as well as check the response headers and data. The command line tool “curl” is standard for most * nix systems. For Windows users, MinGW / MSYS is suitable.

Usage example and basic options:

# curl -X PUT www.foo.com/bar/1 -d "some=var" -d "other=var2" -H "Accept: text/json" -I

-X [METHOD] defines an HTTP method.
-d "name = value" sets the name and values ​​of variables in POST / PUT.
-H [HEADER] sets the header.
-I displays the response headers.

There is also a free, Java / Swing based rest-client for REST testing. It also supports JSON / XML.

Useful links on the topic


Original article in English
Web Development → REST Architecture
The most useful article on REST in English
RESTful PHP framework
REST: the quick pitch
Method Definitions

UPD:

Where one way or another is used


Flickr services
Yahoo! Maps Web Services
Mambo's RESTful API

* restful (eng.) - soothing; calming.

Source: https://habr.com/ru/post/46032/


All Articles