Building RESTful Web Services with PHP 7 - Haafiz Waheed-ud-din Ahmad - E-Book

Building RESTful Web Services with PHP 7 E-Book

Haafiz Waheed-ud-din Ahmad

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn how to build RESTful API and web services in PHP 7



About This Book



  • Leverage the Lumen framework to build RESTful API endpoints for your applications
  • Understand how to increase efficiency and security of your web service.
  • Learn to apply the concepts by implementing the examples covered in the book


Who This Book Is For



This book is for PHP developers who wish to learn about the REST architecture to be able to build and consume REST APIs in their applications.



What You Will Learn



  • Understand the REST API architecture and its benefits
  • Write RESTful API web services in PHP 7
  • Address security-elated issues in a REST API
  • Leverage the importance of automated testing and write tests for API endpoints
  • Identify security flaws in our current API endpoints and tackle them effectively
  • Observe the working of Lumen microframeworks and write RESTful web services in it


In Detail



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.



Style and approach



This book will get you started with REST architecture and will also teach you different methods to build web services from scratch.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 283

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Building RESTful Web Services with PHP 7

 

 

 

 

 

 

 

 

 

 

Lumen, Composer, API testing, Microservices, and more

 

 

 

 

 

 

 

 

 

 

Haafiz Waheed-ud-din Ahmad

 

 

 

 

 

 

 

 

 

 

 

   

BIRMINGHAM - MUMBAI

Building RESTful Web Services with PHP 7

 

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: September 2017

 

Production reference: 1060917

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

 

ISBN 978-1-78712-774-6

www.packtpub.com

Credits

Author

Haafiz Waheed-ud-din Ahmad

Copy Editor

Sameen Siddiqui

Reviewer

Shuvankar Sarkar

Project Coordinator

Vaidehi Sawant

Commissioning Editor

Aaron Lazar

Proofreader

Safis Editing

Acquisition Editor

Chaitanya Nair

Indexer

Francy Puthiry

Content Development Editor

Zeeyan Pinheiro

Graphics

Abhinash Sahu

Technical Editors

Ketan Kamble

Production Coordinator

Nilesh Mohite

 

About the Author

Haafiz Waheed-ud-din Ahmad has been working in the IT industry since 2008. He has mostly worked in web application development and mostly used PHP at the server side. Although most of his experience is in PHP, he is a technology agnostic person and also likes to learn and adapt to new technologies. He also acts as an adviser for startups and new developers.

He has worked on Python and JavaScript as well. He likes to experiment with new technologies, and he has also explored Golang, Scala, and Neo4J. He also has a keen interest in data science and big data domain and has worked on D3.js for data visualization. He is not just a technology enthusiast but also likes to solve day-to-day problems by the usage of technology. He blogs at http://haafiz.me/. You can follow him on twitter at @Haafiz786.

About the Reviewer

Shuvankar Sarkar is an IT Analyst experienced in C#, .NET, PHP, and web development. He is a technology enthusiast and maintains a blog at http://shuvankar.com. You can follow him on Twitter at @sonu041. Shuvankar is interested in computer security as well.

I would like to thank my family for making my life easy and full of happiness.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

 

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Downloading the example code

Errata

Piracy

Questions

RESTful Web Services, Introduction and Motivation

Web services

Why a web service?

REST architecture

Client server

Stateless

Cache-able

Uniform interface

Resource identification

Manipulation of resources through representations

Self-descriptive messages

Hypermedia as the engine of application state (HATEOAS)

Code on demand (optional)

Layered system

RESTful web services

Conventions of RESTful web services

HTTP verbs and URL structure

List operation

Create operation

READ operation

Update operation

Delete operation

Why RESTful web services?

REST versus SOAP

Nature of HTTP methods

Safe/unsafe HTTP methods

Idempotent and non-idempotent methods

HTTP response

Response type

Response codes

Case study - RESTful web service endpoints for a blog

Blog post

Requirements

Endpoints

Creating blog post

Reading blog post

Updating blog post

Delete blog post

Listing all blog posts

Blog post comments

Requirements

Endpoints

Creating the post's comment

Reading a comment

Updating a comment

Deleting a post comment

Listing all comments for a particular post

More resources

Summary

PHP7, To Code It Better

Scalar type declaration

Return type declaration

Null coalescing operator

Spaceship operator

Group use declarations

Generator-related features

What are generators?

Generator return expression

Generator delegation

Anonymous classes

Closure::call()

Errors and exceptions

PHP7.1

Nullable types

Symmetric array destructuring

Support for keys in list()

Multi-catch exception handling

More resources

Summary

Creating RESTful Endpoints

Creating a REST API for a blog in PHP

Creating a database schema

Blog user/author table schema

SQL for users table

Blog post table schema

Blog post comments schema

Creating a RESTful API's endpoint

Code structure

Common components

DB class

Router class

Code sync

Creating blog post endpoints

REST client

To do

Visible flaws

Validation

Solution

Authentication

Solution

Proper 404 pages

Summary

Reviewing Design Flaws and Security Threats

Finding problems in the current code

Structural and design flaws

Missing query builder layer

Incomplete router

Usage of OOP

Separate Configurations from Implementation

Should write tests

Input validation

Handling 404 and other errors

Meta information missing

DB fields abstraction

Security

Securing API endpoints

What is Auth middleware?

Common security threats in RESTful web services

Use of HTTPS

Securing an API key/token

Not passing an access token in the URL

Access token expiration

Limited scope access token

Public and private endpoints

Public API endpoints

Insecure direct object reference

Restricting allowable verbs

Input validation

Available reusable code

Summary

Load and Resolve with Composer, an Evolutionary

Introduction to Composer

Installation

Installation on Windows

Installation on Linux/Unix/OS X

Global Installation

Usage of Composer

Composer as a dependency manager

Installing packages

Installing using composer.json

The composer.json in detail

The require object

The require-dev object

The autoload and autoload-dev

The scripts

The composer.lock

Composer as an auto-loader

Example

Composer for creating a project

Example

Summary

Illuminating RESTful Web Services with Lumen

Introducing Lumen

Why micro-framework?

Why Lumen?

What Lumen provides

What Lumen has in common with Laravel

How Lumen is different from Laravel

What exactly Lumen provides

A Good Structure

Separate configurations

Router

Middle-wares

Service Container and Dependency Injection

HTTP responses

Validation

Eloquent ORM

Database migration and seeding

Unit testing

Installing Lumen

Configuration

Setting up the database

Writing migrations

Writing RESTful web service endpoints

Writing the first controller

Lumen routes

REST resource

Eloquent ORM (model layer)

Creating models

Eloquent relationships

Controller Implementation

What we are missing?

Validation and negative cases?

/api/posts with GET method

/api/posts with the POST method

/api/posts/1 with the GET method

/api/posts/1 with the PATCH/PUT method

/api/posts/1 with the DELETE method

User authentication

Other missing elements

Comment Resource Implementation

Summary

Improving RESTful Web Services

Dingo, simplifying RESTful API development

Installation and configuration

Simplifying routes

API versioning

Rate limiting

Internal requests

Responses

Authentication and middleware

JWT Auth setup

The Manual way

Simpler way through Lumen JWT authentication integration package

Authentication

Log in

Invalidate token

Refresh token

Transformers

Understanding and setting transformers

Using transformers

Encryption

SSL certificate, different options

Summary

API Testing – Guards on the Gates

The need for automated tests

Types of testing

Unit testing

Acceptance testing

Functional testing

Integration testing

What type of testing will we do?

Testing frameworks

CodeCeption introduction

Setup and understanding the structure

tests/{suite-name}/

tests/{suite-name}.suite.yml

tests/_support/_generated/{suite-name}TesterActions.php

tests/_support/{suite-name}Tester.php

tests/_support/Helper/{suite-name}.php

Creating the API suite

Configuring the API suite

Writing test cases

API tests for post resource

Other test cases

Summary

More resources

Microservices

Introducing Microservices

How to divide an application into microservices?

Motivation towards microservices

Maintenance and debugging

Scalability

Technology diversity

Resilience

Replaceability

Parallelization

How it is different from SOA

Team structure

Challenges of micro-services

Infrastructure maintenance

Performance

Debugging and fault-finding

Logs should be centralized

Logs should be searchable

Track chain of requests

Dynamic log levels

Implementation

Deployments

Inter-services communication

Synchronous communication

Asynchronous communication

Shared library or common code

Summary

What's next

Preface

Web services has always been an important topic. With REST, things became simpler and better. Nowadays, RESTful web services are widely used. It was important a decade ago, but Single Page Applications (SPAs) and mobile applications have increased its usage greatly. The aim of this book is to educate PHP developers about the RESTful web services architecture, the current tools available to efficiently create RESTful web services such as a micro-framework named Lumen, automated API testing, the API testing framework, security and microservices architecture.

Although this book is specific to PHP as we will be building RESTful web services in PHP7, it is neither just about PHP7 nor just about REST. RESTful web services and implementation in PHP is what we do in this book. However, you will learn a lot more than that. You will learn about some PHP features that are new in PHP7. We will cover how we should structure our application and some common threats with respect to the web and web services. You will learn how to improve a basic RESTful web service and understand the importance of testing and the different types of testing. So it is not about just REST or PHP, but also about some minor but important programming-related stuff that is simple but makes things a lot better in the real world. At the end of this book, you will learn about an architecture named microservices.

In other words, although this book is intended for PHP developers, it will benefit them beyond just PHP. So, this book is not a cookbook, but a journey in which you start learning about RESTful webservices and PHP7 and then start building RESTful web services. You can then keep improving your RESTful web services by learning about the problems in it and fixing those. During such improvements, you will learn the different things in PHP and benefit even beyond PHP.

What this book covers

Chapter 1, RESTful Web Services, Introduction and Motivation, introduces you to web services, REST architecture, the RESTful web services, and its comparison to other web services such as HTTP verbs and RESTful endpoints. It also explains web services through the example of a blog and then talk about the response format and response code.

Chapter 2, PHP7, To Code It Better, includes new features and changes in PHP7 that we will either use in this book or are very important and worth discussing.

Chapter 3, Creating RESTful Endpoints, is about creating REST API endpoints for CRUD operations of a blog post in Vanilla PHP. It also explains the manual way of testing API endpoints through a REST client named Postman.

Chapter 4, Reviewing Design Flaws and Security Threats, reviews what we have built in the preceding chapter and highlights the problems and flaws in it so that we can improvise later.

Chapter 5, Load and Resolve with Composer, an Evolutionary, is about an evolutionary tool in the PHP ecosystem: composer. This is not just an autoloader or package installer, but a dependency manager. So, you will learn about composer in this chapter.

Chapter 6, Illuminating RESTful Web Services with Lumen, introduces you to a micro-framework named Lumen, in which we will rewrite our RESTful web services endpoints and review how this tool will significantly improve our speed and application structure.

Chapter 7, Improving RESTful Web Services, equips us to improve what we did in the preceding chapter; you will learn how to improve RESTful web services. We will create authentication and make a Transformer to separate how JSON structure should look. Also, we will improve in terms of security and learn about SSL.

Chapter 8, API Testing – Guards on the Gates, introduces the need of automated tests. Will introduce different type of tests and then focus on API testing. We will then cover an automated testing framework named CodeCeption and write API tests in it.

Chapter 9, Microservices, is about the microservices architecture. We will understand the benefits and challenges of microservices and look into some of possible solutions and trade-offs.

What you need for this book

Although I used Ubuntu, any operating system with PHP7 installed on it will work fine. The only thing required other than PHP7 will be an RDBMS. This book uses MySQL-related settings when connecting to database, so MySQL is ideal, but MariaDB or PostgreSQL will also be fine.

Who this book is for

This book is written for the following audience:

Anyone who has some basic PHP knowledge and wants to build RESTful web services.

Developers who know basic PHP and have developed a basic dynamic website and want to build a RESTful web service.

Developers who have learned PHP and worked mostly in open source CMS, such as WordPress, and want to move toward developing custom applications where a web service needs to be built.

Developers who are stuck with legacy systems done in Code Igniter and want to explore the modern ecosystem of PHP.

Developers who have used modern frameworks such as Yii or Laravel, but are not sure about the critical pieces required to build the REST API that not only serves the purpose but works well in the long run, something that doesn't always need manual testing and is maintainable and extendable.

Seasoned PHP developers who have created a very basic API that returns data but want to make themselves familiar with how it should be done according to REST standards, how it will work when authentication comes into the picture, and how to write tests for it.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The randGen() method takes two parameters defining the range of the returned value."

A block of code is set as follows:

<?phpfunction add($num1, $num2)

:int

{ return ($num1+$num2);}echo add(2,4); //6echo add(2.5,4); //6

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<?phpfunction add($num1, $num2)

:int

{

return ($num1+$num2);

}echo add(2,4); //6echo add(2.5,4); //6

Any command-line input or output is written as follows:

sudo add-apt-repository ppa:ondrej/php

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text.

Warnings or important notes appear like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-RESTful-Web-Services-with-PHP-7. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

RESTful Web Services, Introduction and Motivation

RESTful web services are being used widely nowadays. RESTful is simple and most widely used among other web services. In fact, its simplicity is a reason for its fame as well. If you are reading this book, then chances are that you know something about RESTful web services. You probably have used it or you have just heard of it. But even if you don't know much about RESTful web services, don't worry as we are first defining it right here. So first, let's list the high level topics that we will be covering in this chapter:

Web services, what is a web service?

REST architecture (constraints of REST)

RESTful web services

Conventions of RESTful web services

HTTP verbs (methods)

Why RESTful web services?

Response type and response codes

Case study - RESTful web service endpoints for a blog

However, there are a lot of misconceptions about RESTful web services. For example, some people think that anything over the web returning JSON is a RESTful web service and RESTful web services only return JSON. This is not true.

In fact, RESTful web services support multiple formats and not everything returning JSON is a RESTful web service. To avoid confusion, let us understand what RESTful web service is.

A web service based on the REST architecture is a RESTful web service.So, what exactly is a web service and REST architecture? Let's start by understanding web service first and then the REST architecture.

Web services

Web services are defined differently at different places. Word-by word translation states that any service provided on the web including a web page is a web service but this isn't true if the technical term web service is referred to.

To define web service, we will look at web service definition from the W3C glossary:

"A Web service is a software system designed to support inter-operable machine-to-machine interaction over a network. It has an interface described in a machine-process able format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP-messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards." -W3C, web services glossary.

This definition again, is not completely true as it is more specific to SOAP and WSDL based web services. In fact, later in the W3C Working Group Note, February 11, 2004, it was stated that:

"We can identify two major classes of web services:- REST-compliant web services, in which the primary purpose of the service is to manipulate XML representations of Web resources using a uniform set of "stateless" operations; - and arbitrary web services, in which the service may expose an arbitrary set of operations."

So considering that, a more general and better definition of a web service is this, from the preceding mentioned W3C web services glossary definition:

"A Web service is a software system designed to supportinter-operablemachine-to-machine interaction over a network."

Why a web service?

Now, we know what a web service is. So before proceeding to REST, it is important to know the need for a web service. Where can a web service be used?

As just defined, a web service is a system to support machine-to-machine inter-operable communication over a network. It is very useful for communication between different systems or devices. In our case, we will be using web services to provide an interface by which either a mobile application or a web application will be able to communicate with a server to get and store data. This will make the client-side application separate from the server side logic. And nowadays, SPAs (Single Page Applications) and mobile applications need to be stand alone, separate from server side and only interacting with server side logic with web services. So definitely web services are very much important nowadays. However, web service usage is not limited to client side application usage but it is also useful in server to server communication where one server acts as a client.

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 for 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 about the user interface. So both the server and client 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 this 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 results 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 service 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 decouples the architecture makes the interface separate from the implementation, just as any good 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 stored 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 stores 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 the 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 able 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 client knows an entry point then from that first endpoint, it should be able to discover other 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 to 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 server sends to the browser.

Let's consider an example to understand this better.