PHP Serving RESTful APIs Introduction - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Serving RESTful APIs Introduction - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, June 20, 2019

PHP Serving RESTful APIs Introduction

PHP Serving RESTful APIs


Introduction


Exposing APIs using REST allows practically everyone to programmatically access your application. It doesn’t matter what language they’re using. Because REST embraces the basic protocol of the Web as its syntax, no special libraries are necessary. If a developer is capable of making HTTP requests, he can call your RESTful APIs.

REST does not prescribe a specific syntax for requests, the schema of the data passed back and forth, or even how to serialize data. Instead, it’s an architectural style that provides a set of patterns and general rules. Each site is then free to implement its APIs according to its needs, as long as it can follow the guidelines.

A resource is the fundamental unit of REST. Resources can be people, objects, or anything you wish to act upon. Resources are identified by location, using URLs. (Or by name, using a URN.)1 Resources have representations, which are various ways to describe the resource. Usually the representations use standard data formats, such as JSON, XML, HTML, PDF, PNG, etc.

It’s a standard pattern to format URLs using /version/resource/key. For example, Rasmus Lerdorf could be located at http://api.example.com/v1/people/rasmus. This maps to a person identified as “rasmus” using version 1.0 of the API.

This resource can be represented in JSON as:

     {
          "firstName": "Rasmus"
          "lastName": "Lerdorf"
     }

In REST, the HTTP methods, such as GET and POST, describes the requested action. So, to process a RESTful request you need to know both the URL and the HTTP method. Demonstrates how to route a request to a URL based on the client’s HTTP method, and shows to do so with “clean” URLs.

Each method has a well-defined set of behaviors. For example, GET tells the server you want to retrieve an existing resource, whereas POST means you want to add a new resource. You use PUT to modify a resource or create a specifically named resource. And DELETE, of course, deletes the resource.

Beyond this, REST imposes a few other constraints upon your API design. Specifically, some methods must be safe and others must be idempotent.

Safe methods, such as GET, don’t modify resources (which is why they’re safe). Other methods, such as POST and DELETE, are not safe. They are allowed to have the side effect of updating the system, by creating, modifying, or deleting a resource (which is probably what you want, but it isn’t safe).

Nonsafe methods are further subdivided into two based on idempotency. When a method is idempotent, calling it multiple times is equivalent to calling it once. For instance, once you’ve called DELETE on a resource, trying to DELETE it again may return an error, but won’t cause anything else to be deleted. In contrast, making a POST request twice can cause two new resources to be created. Table provides an outline of this behavior.

Table  HTTP method behavior

HTTP method   Description          Safe Idempotent 
GET                         Read a resource       Yes    Yes
POST                       Create a resource    No     No
PUT                         Update a resource   No     Yes
DELETE                 Delete a resource     No    Yes
_______________________________________

Detailed specifics of how each method behaves and how to process requests for reading, creating, updating, and deleting a resource.

REST uses HTTP status codes to indicate whether the request has succeeded or failed. The 200s indicate success; 300s indicate further action is needed for the server to respond; 400s are client errors; and 500s are server errors. For example, a GET request that’s successful returns 200; a request to a resource that’s at a new URL returns 301, trying to read a nonexistent resource returns 404, and a request to a server undergoing maintenance returns 503.

Common status codes and when it’s appropriate to use them are described in the context of recipes as appropriate. General best practices for returning errors.

It’s perfectly okay for a resource to have multiple representations. An XML version of http://api.example.com/v1/people/rasmus could be:

       <person>
            <firstName>Rasmus</firstName>
            <lastName>Lerdorf</lastName>
       </person>

Another example is a text document that has both an HTML and a PDF version, or an image that comes in both JPEG and PNG formats. How to expose the same resource in more than one way.

The recipes in this chapter look to provide the foundation for designing and implementing RESTful APIs in PHP. However, the entirety of that task is far beyond the scope of a single chapter. REST has many aspects, including caching and hypermedia as the engine of application state (HATEOAS) that aren’t touched upon. To learn more, you can go to the source: the original document describing REST is Roy Fielding’s thesisNot unexpectedly, this is somewhat academic in nature.

A more practical book that still looks to translate the tenets of REST into specifics is RESTful Web APIs by Leonard Richardson, Mike Amundsen, and Sam Ruby (O’Reilly). REST in Practice by Jim Webber, Savas Parastatidis, and Ian Robinson (O’Reilly) is a pragmatic hands-on guide to RESTFul design. Finally, a very in-depth Cookbook style guide to REST is RESTful Web Services Cookbook by Subbu Allamaraju (O’Reilly). Chapter 8 covers how to implement additional RESTful concepts, although without necessarily using RESTful terminology. For example, authentication and reading and writing HTTP headers.

Though an understanding of the fundamentals of RESTful design is necessary to create a RESTful API of your own, you don’t need to implement all the scaffolding code from scratch. Unfortunately, there’s no one-size-fits-all official PHP RESTful framework. (Some may quip that’s PHP itself.) However, there are a number of PHP frameworks to simplify the overhead of exposing resources. Some are full MVC frameworks with ORM abstractions to enable the creation of fullstack applications that also expose RESTful APIs; others are micro-frameworks that provide the thinnest facade on top of your existing code. This is an area of active development, so you’re bound to find a package that’s perfect for your situation.



No comments:

Post a Comment

Post Top Ad