Book Image

Building RESTful Web Services with PHP 7

By : Waheed ud din
Book Image

Building RESTful Web Services with PHP 7

By: Waheed ud din

Overview of this book

REST is the most wide spread and effective standard to develop APIs for internet services. With the way PHP and its eco-system has modernized the way code is written by simplifying various operations, it is useful to develop RESTful APIs with PHP 7 and modern tools. This book explains in detail how to create your own RESTful API in PHP 7 that can be consumed by other users in your organization. Starting with a brief introduction to the fundamentals of REST architecture and the new features in PHP 7, you will learn to implement basic RESTful API endpoints using vanilla PHP. The book explains how to identify flaws in security and design and teach you how to tackle them. You will learn about composer, Lumen framework and how to make your RESTful API cleaner, secure and efficient. The book emphasizes on automated tests, teaches about different testing types and give a brief introduction to microservices which is the natural way forward. After reading this book, you will have a clear understanding of the REST architecture and you can build a web service from scratch.
Table of Contents (16 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

REST architecture


REST stands for Representational State Transfer. It is an architectural style founded by Roy Fielding in 2000 and was stated in his PhD dissertation. He stated that REST

"provides a set of architectural constraints that, when applied as a whole, emphasizes scalability of component interactions, generality of interfaces, independent deployment of components, and intermediary components to reduce interaction latency, enforce security, and encapsulate legacy systems."

.

REST is an architectural style a network-based application and HTTP 1.1 was based on it, as it was developed in parallel to HTTP 1.1.

A RESTful system or RESTful web service must abide by the following six constraints; otherwise, it will not be considered as RESTful or REST-compliant. While reading and understanding the following mentioned constraints, think about the modern web as an example of REST architecture.

Client server

REST is about separating the client and server. This constraint is about "separation of concerns". It means that the server and client have separate responsibilities, so one is not responsible for the other's duties. For example, the client is not responsible for data storage on the server as it is the server's responsibility. In the same way, the server doesn't need to know the user interface. So both the server and perform their tasks and fulfill their own responsibilities which makes their work easier. Hence, the server can be more scalable and the user interface on the client can be independent and more interactive.

Stateless

Client server communication is stateless. Each request coming from the client will have all the information required to serve a request. This means there is no state in communication other than what is in the request. The response which the client will get will be based on the request without looking at any state other than what is in request.

If the session needs to be maintained, the session will be stored based on a token or identifier which is coming in the request. So if we look at an example of a web request, then the flow of HTTP is no more than a request sent by the client to the server and a response, sent back to the client from the server, as shown in the following diagram:

If a session needs to be maintained, the session data will be stored on the server, while the session identifier will be sent back to the client. In subsequent requests, the client will include that session identifier in every request by which the server will identify the client and load the related session's data as explained in the following diagram:

And in subsequent requests:

So REST is stateless. To maintain the state, one needs to pass an identifier or any other information, to logically group different requests to maintain a session in the request. If no such identifier is passed in the request, the server will never know if those two requests are from same client.

The advantage of statelessness is simplicity. The same requests will not result in different responses unless the request parameters are changed. It will return different based on different request parameters not due to some sort of state. Even the state depends on requests, as shown in the preceding example. So that session identifier is in the request, which can result in a different state and, hence, results in a different response.

Cache-able

This constraint specifies that a RESTful web response must define itself as cache-able or not, so that the client can know whether it should be cached or not. If it is correctly defined, it can result in less overhead and better performance because the client will not go to the server if it is able to use the cached version.

Uniform interface

The uniform interface is the most distinguishing constraint. It basically the architecture makes the interface separate from the implementation, just as any system does.

It is similar to how it is in OOP: an interface separates the implementation and declaration. It is similar to how an operating system separates the user interface from the complex implementation logic that keeps our software's running.

The uniform interface has four constraints. In order to understand uniform interface, we need to understand these constraints.

Resource identification

Resources will be identified in requests. For example, a resource in a web-based REST system will be identified by the URI. And no matter how a resource is on the server, it will remain separate from what will be returned to the client in the response.

In fact, resource storage on the server is an implementation but the request and response is what a client is interacting with, so it is like an interface to the client. And a client can identify a resource by this interface. So all that a client knows is what it is requesting and getting in response.

For example, a client usually sends a request to the URI and gets a response in the form of HTML, JSON, or XML. None of these formats are how the server data internally in the database or somewhere else on the server. But for a client, it is the URI where it will hit and the HTML, JSON, and XML is what it gets.

This is what a resource is for a client, no matter how it is stored on the server. And this is the benefit, because no matter if the server's internal logic or representation is changed, for the client it will remain the same because the client sends the request to the URI and gets a response in the form of HTML, JSON, or XML and not how it is stored on the server. This constraint, results in loose coupling of resource identification and representation.

Manipulation of resources through representations

This constraint states that the client should hold representation of a resource that has enough information to modify or delete the resource. For example, in the web-based REST system, any operation can be performed on a resource using the HTTP method and URI. This makes things easy to follow, as the API developer doesn't need to provide documentation for each and every endpoint related to a resource.

Self-descriptive messages

This constraint states that each message should be to be processed based on information contained in itself. That means, every message passed between the server and client should be stateless be independent of other messages. One message doesn't have an impact on other messages. So, it doesn't matter if two messages are passed in some particular order or not, as they are independent. The request in a message is enough to get a response and that response has all that needs to be conveyed.

Hypermedia as the engine of application state (HATEOAS)

This constraint states that, based on what a server provides to a REST client, the REST client should be able to discover all available actions and resources. In other words, it states that if a knows an entry point then from that first endpoint, it should be able to discover relevant endpoints related to that resource. For example, if a client goes to a resource's listing endpoint, that should include links to resources in that listing. And if there is pagination or limit being applied, it should have links to go to the rest of the items in the listing.

If a client has created a new resource, the new resource's link should be included in response as well which can be used for read, update, and delete operations on that resource by using different HTTP verbs. For operations other than typical CRUD, it will obviously have more URLs, so URLs for those operations should also be in the response, so that all endpoints related to the resource can be discoverable from one entry point.

Due to HATEOAS, an endpoint exposes links to related endpoints. This reduces the need of a thorough API documentation, although not completely, but one does not need to see the API documentation for the links already being exposed.

Code on demand (optional)

This states that the server can add more functionality the REST client, by sending code that can be executable by that client. In the context of the web, one such example is JavaScript code that the sends to the browser.

Let's consider an example to understand this better.

For example, a web browser acts like a REST client and the server passes HTML content that the browser renders. At the server side, there is some sort of server-side language which is performing some logical work at the server side. But if we want to add some logic which will work in the browser then we (as server-side developers) will have to send some JavaScript code to the client side and the browser and then execute that JavaScript code. So that the JavaScript code can add validation to a form, some animation or anything else, that couldn't be possible simply in HTML content. That JavaScript code is code on demand which the server sends to the client that extends the functionality of the REST client.

Note that sending code on demand to the client is optional, and not required if we don't want to extend the client's functionality.

Layered system

This constraint states that the REST system can multiple layers and if a is requesting for a response and getting a response, it can't be differentiated if it was returned from the server or another middle-ware server. So if one server layer is replaced by an other, it doesn't affect the client unless it provides what it is expected to provide. In short, one layer doesn't have knowledge beyond the next layer with which it is interacting directly.