Create a RESTful API in PHP?

I developed a very fast and simple PHP application for reading classified ads from an XML file and allowing the user to perform CRUD operations (this was homework).

I am now tasked with developing this application for the RESTful service. The professor apparently does not have any experience with RESTful services, because he said that my application was found to transmit the next assignment, when my studies show that he does not really fulfill all the RESTful requirements.

Regardless, I want to do it right for training purposes, even if I can transfer my old assignment and get a good class. I am having trouble learning where to start; I don’t know exactly what a RESTful service is.

I think the best way to get advice is to send a sample code from my previous assignment to see how I handled things and how I need to handle things.

For example, here's how I create new ads.

create.php

//Basically just a list of <INPUT TYPE = "text" NAME = "something"> in the <body> fields 

CreateSuccess.php

 <html><head><?php $simplerXML = simplexml_load_file('file.xml'); //Generate the basic ad information $newAd = $simplerXML->addChild('advertisement',''); $newAd->addAttribute('category', $_POST["category"]); $title = $newAd->addChild('title', $_POST["title"]); $title->addAttribute('ID', $_POST["ID"]); $pageTitle = $newAd->addChild('pagetitle', $_POST["pagetitle"]); //etc, for all the SUBMIT boxes //save the XML $simplerXML->asXML('file.xml'); echo "<script type='text/javascript'> //redirect back to ad listing page window.onload = function () { top.location.href = 'ads.php'; }; </script>"; ?></head> <body></body></html> 

I also use URL parameters for RUD actions. I heard that URL parameters are not allowed?

Thanks.

EDIT: So, the SWITCH instruction, does it go to the index.php file? And then each case will call a function, i.e. CreateXML for the POST method? Then does he need parameters such as an object type, an object identifier, and a content type? How do I get the values ​​for updating XML, I just sent it to the Create.php file containing a list of input fields?

+7
source share
2 answers

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:

  • Post
  • Get
  • Put
  • DELETE

and you can optionally support

  • PATCH
  • HEAD

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"]; // Route from here to a class with the name of the object (eg UserController) via __autoload // or to a file (eg user.php) via include, and pass id and content_type as params 

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!

+15
source

"RESTful" is a broad concept, and there are degrees of "RESTfulness". Wikipedia is a good guide here

Here are some higher-level characteristics that are not covered in another answer (which is also good):

  • Resources are accessible at URLs, preferably with one canonical URL per resource.
    • You can indicate that the resource is available in other URLs or views using the Content-Location header.
    • You can provide various representations of the resource (html, json, xml, etc.) using content matching with Accept and content-type headers.
  • Resource state changes are fully represented by a single HTTP request. The server does not need to maintain state to serve the client request. Therefore, requests can be easily proxied and cached.
    • An example of a general violation of this principle is a URL, for example "http://example.org/profile", which serves a different user profile depending on who is logged in.
    • It would be better to separate the resource from authorization: "http://example.org/profile/{USERID" "will always serve a specific user ID, but returns 401 (not authorized) if the client does not have permission, (In addition, the information an authorization must be sent with every request, so that the server does not require a session token or a similar state on the server side.As a result, most websites with cookie-based login systems do not just calm down.)
    • GET to get the resource. This should not change the state of the resource and should be safely reproducible. This property is often called "Idempotency."
    • PUT to update the resource. Using methods such as conditional update requests (PUT or DELETE with an if-* header), you can even implement an optimistic concurrency control.
    • DELETE to delete a resource.
    • POST as a "do something" resource. POST is used when you need to do something that does not correspond purely to http methods or when you need to perform an action with side effects (for example, create a new resource without knowing its name or implement the RPC protocol). However, you should use http headers and response codes to show what side effects were there, for example a “201 created” with Location and Content-Location headers and a list of URLs affected by the change.
  • Resource representations are self-describing "hypertexts" with links to other resources.
    • An example of a violation of this principle: suppose that "http://example.com/articles" is a list of articles, and the json representation looks like [1,2,3,4,5,6] . This is a list of article identifiers, but it is not self-describing or hypertext - the client needs to know that this is a list of article identifiers, and he needs to know that in order to get the article resource he must build a URL, for example, http://example.org/ articles / 1 ".
    • A better answer would be like {"articles":[{"id":1,"url":"http://example.org/articles/1"},...]} . Like html, a client using a leisure service only needs to follow the links (do not create links) to gain access to other related resources. You can even document the available methods that you can use to manage the resource — create, update, delete, etc.
+4
source

All Articles