Building RESTful Web Services with .NET Core - Gaurav Aroraa - E-Book

Building RESTful Web Services with .NET Core E-Book

Gaurav Aroraa

0,0
31,19 €

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

Building Complete E-commerce/Shopping Cart Application

Key Features

  • Follow best practices and explore techniques such as clustering and caching to achieve a reactive, scalable web service
  • Leverage the .NET Framework to quickly implement RESTful endpoints.
  • Learn to implement a client library for a RESTful web service using ASP.NET Core.

Book Description

REST is an architectural style that tackles the challenges of building scalable web services. In today's connected world, APIs have taken a central role on the web. APIs provide the fabric through which systems interact, and REST has become synonymous with APIs. The depth, breadth, and ease of use of ASP.NET Core makes it a breeze for developers to work with for building robust web APIs. This book takes you through the design of RESTful web services and leverages the ASP.NET Core framework to implement these services. This book begins by introducing you to the basics of the philosophy behind REST. You'll go through the steps of designing and implementing an enterprise-grade RESTful web service. This book takes a practical approach, that you can apply to your own circumstances. This book brings forth the power of the latest .NET Core release, working with MVC. Later, you will learn about the use of the framework to explore approaches to tackle resilience, security, and scalability concerns. You will explore the steps to improve the performance of your applications. You'll also learn techniques to deal with security in web APIs and discover how to implement unit and integration test strategies. By the end of the book, you will have a complete understanding of Building a client for RESTful web services, along with some scaling techniques.

What you will learn

  • Add basic authentication to your RESTful API
  • Create a Carts Controller and Orders Controller to manage and process Orders
  • Intercept HTTP requests and responses by building your own middleware
  • Test service calls using Postman and Advanced REST Client
  • Secure your data/application using annotations

Who this book is for

This book is intended for those who want to learn to build RESTful web services with the latest .NET Core Framework. To make best use of the code samples included in the book, you should have a basic knowledge of C# and .NET Core.

Gaurav Aroraa Gaurav Aroraa has an M.Phil in computer science. He is a Microsoft MVP, a lifetime member of Computer Society of India (CSI), an advisory member of IndiaMentor, certified as a scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. Gaurav is an open source developer, a contributor to TechNet Wiki, and the founder of Ovatic Systems Private Limited. In 20+ years of his career, he has mentored thousands of students and industry professionals. You can tweet Gaurav on his Twitter handle @g_arora. Tadit Dash Tadit Dash is a senior software engineer and a hardcore tech community contributor. Due to his exceptional contribution to the technical community, Microsoft has awarded him with the Microsoft Most Valuable Professional accolade since 2014. CodeProject has awarded him the CodeProject MVP accolade (the first from Odisha). For his constant mentorship, IndiaMentor featured him as a young mentor on their site. He was a featured speaker at DevTechDay Nepal and C# Corner Annual Conference, India. You can follow him on Twitter: @taditdash.

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 259

Veröffentlichungsjahr: 2018

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 .NET Core

 

 

 

 

 

 

Developing Distributed Web Services to improve scalability with .NET Core 2.0 and ASP.NET Core 2.0

 

 

 

 

 

 

 

Gaurav Aroraa
Tadit Dash

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Building RESTful Web Services with .NET Core

Copyright © 2018 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Aaron LazarAcquisition Editor: Denim PintoContent Development Editor: Anugraha ArunagiriTechnical Editor: Jash BavishiCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Mariammal ChettiyarGraphics: Tania DuttaProduction Coordinator: Shantanu Zagade

First published: May 2018

Production reference: 1290518

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

ISBN 978-1-78829-157-6

www.packtpub.com

 

To my mother, Late Smt. Santosh, and to the memory of my father, Late Sh. Ramkrishan, for their sacrifices and for exemplifying the power of determination. To my youngest sister Late Baby Kanchan for her love and always being my lucky charm.

– Gaurav Aroraa

 

To my grandfather late Ganeswar Tripathy, for consistently motivating me.To my father, Dr. Gobinda Chandra Dash, and mother, Mrs. Sasmita Tripathy, for whatever they have sacrificed in their life to build me.

– Tadit Dash
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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.

Contributors

About the authors

Gaurav Aroraa has an M.Phil in computer science. He is a Microsoft MVP, a lifetime member of Computer Society of India (CSI), an advisory member of IndiaMentor, certified as a scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. Gaurav is an open source developer, a contributor to TechNet Wiki, and the founder of Ovatic Systems Private Limited. In 20+ years of his career, he has mentored thousands of students and industry professionals. You can tweet Gaurav on his Twitter handle @g_arora.

To my wife, Shuby Arora, and my angel (daughter), Aarchi Arora, who permitted me to steal time for this book from the time I was supposed to spend with them. Thanks to the entire Packt team, especially Ulhas, Vikas Tiwari, Anugraha Arunagiri, and Jash Bavishi, whose coordination and communication during the period was tremendous, and Denim Pinto, who introduced me for this book.

 

 

Tadit Dash is a senior software engineer and a hardcore tech community contributor. Due to his exceptional contribution to the technical community, Microsoft has awarded him with the Microsoft Most Valuable Professional accolade since 2014. CodeProject has awarded him the CodeProject MVP accolade (the first from Odisha). For his constant mentorship, IndiaMentor featured him as a young mentor on their site. He was a featured speaker at DevTechDay Nepal and C# Corner Annual Conference, India. You can follow him on Twitter: @taditdash.

To Utkal Techies Forum members Suvendu Giri, Pravasini Sahoo, Suraj Sahoo, Surya Barik, Abhijit Pattnaik, Sourav Nanda, Jayant Rajwani, Ramesh Barik; my friends Manas Pritam, Deepak Mahapatra; my cousins Lipsa, Aurobin, Titiksha, Juthika, Amrit, Sanvi, Anushka, Swostik; my mentor Gaurav Arora; and the Packt team, Denim Pinto, Vikas Tiwari, Anugraha Arunagiri, and Jash Bavishi.

About the reviewer

Hansamali Gamage is an experienced professional and Microsoft MVP in Visual Studio and Technologies from Sri Lanka. She possesses 5+ years of experience in .NET stack and Azure-related services. She is a frequent speaker at local and global tech events. She is a tech enthusiast and an award-winning writer on the Microsoft Tech Net forum. She works at TIQRI, previously known as Exilesoft, which is technology-focused software engineering company that has offices in Scandinavia, Asia, and Australia.

I would like to thank my loving family for their continuous help and support.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Building RESTful Web Services with .NET Core

Dedication

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Getting Started

Discussing RESTful services

REST characteristics

Resource-oriented architecture

URI

REST constraints

Client-server architecture

Stateless

Caching

Code on demand (optional)

Uniform interface

More explanation

POST versus PUT explained

Layered system

Advantages and disadvantages of RESTful services

Advantages

Disadvantages

ASP.NET Core and RESTful services

Summary

Building the Initial Framework – Laying the Foundation of the Application

SOAP

SOAP structure

Important points about SOAP

SOAP with HTTP POST

REST

Server and client are independent

Statelessness

Setting up the environment

Running the application

What's cooking here?

Interesting facts

Conclusions

Request and response

HTTP verbs

Postman

GET

Status codes

ASP.NET Core HTTP attributes

POST

PUT

DELETE

SOAP versus REST

Single-page application model

Service-oriented architecture

Summary

User Registration and Administration

Why authentication and limiting requests?

Database design

User registration

Setting up EF with the API

Configuring DbContext

Generating the controller

Calling the API from a page to register the customer

CORS

Adding basic authentication to our REST API

Step 1 – Adding the (authorize) attribute

Step 2 – Designing BasicAuthenticationOptions and BasicAuthenticationHandler

Step 3 – Registering basic authentication at startup

Adding OAuth 2.0 authentication to our service

Step 1 – Designing the Config class

Step 2 – Registering Config at startup

Step 3 – Adding the [Authorize] attribute

Step 4 – Getting the token

Step 5 – Calling the API with the access token

Step 6 – Adding the ProfileService class

Client-based API-consumption architecture

Summary

Item Catalogue, Cart, and Checkout

Implementing controllers

Generating models

Generating controllers

Product listing

Product searching

Adding to cart

Implementing security

Client-side AddToCart function

API calls for AddToCart

POST – api/Carts

PUT – api/Carts/{id}

DELETE – api/Carts/{id}

Placing orders

UI design for placing an order

The client-side PostOrder function

Building order objects to match the model class Orders.cs

Pushing cart items into an order object as an array

Calling POST /api/Orders

PostOrders API POST method

Exposing shipping details

Summary

Integrating External Components and Handling

Understanding the middleware 

Requesting delegates

Use

Run

Map

Adding logging to our API in middleware

Intercepting HTTP requests and responses by building our own middleware

JSON-RPC for RPC communication

Request object

Response object

Summary

Testing RESTful Web Services

Test paradigms

Test coverage and code coverage

Tasks, scenarios, and use cases

Checklist

Bugs and defects

Testing approach

Test pyramid

Types of tests

Testing the ASP.NET Core controller (unit testing)

Getting ready for the tests

Writing unit tests

Stubs and mocking

Security testing

Integration testing

Run tests

Fake objects

Run tests

Testing service calls using Postman, Advanced REST Client, and more

Postman

Advanced Rest Client

User acceptance testing

Performance or load testing

Run tests

Summary

Continuous Integration and Continuous Deployment

Introduction – deployment terminology

The build stage

Continuous integration 

Deployment

Continuous deployment

Continuous delivery

Build and deployment pipeline

Release

Prerequisites for successful RESTful services deployments

The Azure environment

Cloud computing

The benefits of the cloud

Cloud-computing service models

Discussing the Azure environment

Starting with Azure

Publishing/hosting

Project hosting

The dashboard

Code

Work

Adding code to the repository

Test

Creating a test plan

Creating test cases

Running manual tests

Wiki

Build and Release tab

CI versus CD

CI and CD using TFS online

Initiating the CD release process

Summary

Securing RESTful Web Services

OWASP security standards

 Securing RESTful web services

The vulnerable areas of an unsecured web application

Cross-site scripting attacks

SQL injection attacks

What is cooking here?

Fixing SQL injection attacks

Cross-site request forgery

Authentication and authorization in action

Basic authentication, token-based authorization, and other authentications

Basic authentication

The security concerns of basic authentication

Token-based authorization

Other authentication methods

Securing services using annotations

Validations

Securing context

Data encryption and storing sensitive data

Sensitive data

Summary

Scaling RESTful Services (Performance of Web Services)

Clustering

Load balancing

How does it work?

Introduction to scalability

Scaling in (vertical scaling)

Scaling out (horizontal scaling)

Linear scalability

Distributed caching

Caching persisted data (data-tier caching)

First-level caching

Second-level caching

Application caching

CacheCow

Memcached

Azure Redis Cache

Communication (asynchronous)

Summary

Building a Web Client (Consuming Web Services)

Consuming RESTful web services

Building a REST web client

Cooking the web client

Writing code

Implementing a REST web client

Summary

Introduction to Microservices

Overview of microservices

Microservice attributes

Understanding microservice architecture

Communication in microservices

Synchronous messaging

Asynchronous messaging

Message formats

Why we should use microservices

How a microservice architecture works

Advantages of microservices

Prerequisites of a microservice architecture

Scaling

Vertical scaling

Horizontal scaling

DevOps culture

Automation

Testing

Deployment

Microservices ecosystem in ASP.NET Core

Azure Service Fabric – microservice platform

Stateless and Stateful services – a service programming model

Communication – a way to exchange data between services

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

This book will take the readers through the design of RESTful web services and leverages the ASP.NET Core Framework to implement these services. Starting from the basics of the philosophy behind REST, the readers will go through the steps of designing and implementing an enterprise-grade RESTful web service. Taking a practical approach, each chapter provides code samples that they can apply to your own circumstances. It brings forth the power of the latest .NET Core release, working with MVC. It then goes beyond the use of the framework to explore approaches to tackle resilience, security, and scalability concerns. The readers will learn techniques to deal with security in Web APIs and discover how to implement unit and integration test strategies. Finally, the book ends by walking you through building a .NET client for your RESTful web service, along with some scaling techniques.

Who this book is for

This book is intended for those who want to learn to build RESTful web services with the latest .NET Core Framework. To make best use of the code samples included in the book, you should have basic knowledge of C# and .NET Core.

What this book covers

Chapter 1, Getting Started, will cover the planning phase, explain how to identify a perfect technology stack based on our requirement or problem statements, along with fundamental aspects of RESTful and RESTless services.

Chapter 2, Build Initial Framework – Layout Foundation of Application, will get you acquainted with the concepts of various methods, such as GET, POST, PUT, DELETE, and so on. 

Chapter 3, User Registration and Administration, will get you acquainted with authentication with ASP.NET Core 2.0, Entity Framework Core, Basic Authentication, and OAuth 2.0.

Chapter 4, Item Catalogue, Cart, and Checkout, will help you understand the complex components of ASP.NET Core, including .NET Standard 2.0 while building different sections of the e-commerce application.

Chapter 5, Integrating External Components and Handling, will help you understand middleware, implementing logging using middleware, authentication, and resource restriction.

Chapter 6, Testing RESTful Web Services, will get you acquainted with the test paradigm, testing concepts, stubs and mocking, security testing, and integration testing. 

Chapter 7, Continuous Integration and Continuous Deployment, will get you acquainted with CI and CD concepts using VSTS and Azure. 

Chapter 8, Securing RESTful Web Services, will help you understand various security techniques, including basic authentication, XSS attacks, data encryption.

Chapter 9, Scaling RESTful Services (Performance of Web Services), will explain scaling-in, scaling-out, and the various patterns of scaling.

Chapter 10, Building a Web Client (Consuming Web Services), will teach the readers ASP.NET Core and Rest Client with RestSharp.

Chapter 11, Introduction to Microservices, gives an overview of microservices by covering ecosystem in microservices with ASP.NET Core.

To get the most out of this book

The reader should have prior knowledge of .NET Core and .NET Standard, along with basic knowledge of C#, RESTful Services, Visual Studio 2017 (as an IDE), Postman, Advanced Rest Client, and Swagger.

To set up the system, readers should have following on their machines:

Visual Studio 2017 Update 3 or later (for download and installation instructions refer to 

https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio

)

SQL Server 2008 R2 or later (for download and installation instructions refer to 

https://blogs.msdn.microsoft.com/bethmassi/2011/02/18/step-by-step-installing-sql-server-management-studio-2008-express-after-visual-studio-2010/

)

.NET Core 2.0

Download: 

https://www.microsoft.com/net/download/windows

Installation instructions: 

https://blogs.msdn.microsoft.com/benjaminperkins/2017/09/20/how-to-install-net-core-2-0/

 

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the SUPPORT tab.

Click on Code Downloads & Errata.

Enter the name of the book in the Search box and follow the onscreen instructions.

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-DOTNET-Core. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it from https://www.packtpub.com/sites/default/files/downloads/BuildingRESTfulWebServiceswithDOTNETCore_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Getting Started

Modern web development demands interaction with servers without any hassle. What this means is that with the evolution of different UI and backend frameworks, developers need to find a way of sharing data with any available framework without any dependencies. This means there should be a way of sharing data from the server with clients, irrespective of their language and framework. To bring a uniformity to sharing data, the first thing that comes to mind is .xml and .json. These formats are supported by every framework.

In this chapter, we will look at an architectural style by which we can get or send data from any program written in any language using any framework. With REST, the architecture we will be discussing, we can bring in methods that can be easily consumed by clients for data operations.

This chapter will cover the following topics:

RESTful services

Why should we use RESTful services? The difference between RESTful and RESTless services

Client-server architecture

ASP.NET Core and RESTful services

Discussing RESTful services

REST stands for representational state transfer. It is an architectural style that defines a set of guidelines for building web services.

What is an architectural style? It's nothing but a concept with predefined principles. We will talk about these principles in a moment. When you follow REST, you are actually implementing the principles that are the building blocks of REST in your application.

However, the implementation of REST will definitely differ from developer to developer. There is no fixed implementation style. Don't get confused with architectural patterns, which are not concepts but the actual implementations. MVC is an architectural pattern as it has a fixed structure that defines how the components interact with each other where they can't be differently implemented. 

The following is a very simple diagram of a REST-based service:

To simplify things, consider the preceding diagram, which shows you a service that has certain methods, such as GET, POST, PUT, and DELETE. That is what this style is all about. When you design your service, which will have all these methods—with the intended operations inside them—we can consider it as a REST-based service, otherwise known as a RESTful service. More importantly, the service can be called from an application built in any platform and language as the service has a standard architecture.

As discussed, a RESTful service is a service that supports REST. Let's talk about the characteristics of REST so that we can understand what is expected from a service that is RESTful.

REST characteristics

The main building blocks of web services are the client and server architectures. The response sent from the server is actually a reply to the client's request. It's like you are asking a question and the server responds if it finds the answer. The response that comes from the server is actually a resource in a certain format or representation. The formats that are usually seen are .json, .xml, .pdf, .doc, and so on. 

REST is stateless. Stateless means that the state of the system is always different. So, when a request comes to the server, it is served and forgotten. Thus, the next request does not depend on the state of the previous one. Each request is handled by the server independently.

The requests are performed in an HTTP connection. They each take the form of a uniform resource identifier (URI). This identifier helps us to locate the required resource on the web server.

Roy Fielding’s PhD dissertation, entitled Architectural Styles and the Design of Network-Based Software Architectures, defined REST. The following are some key points extracted from his research:

Like many distributed architectures, REST imposes layers, statelessness, and caching.

REST improves efficiency, interoperability, and overall performance.

REST introduces uniformity by following a set of rules on how to identify and manipulate resources, along with the process to simplify the description about its operations through metadata so that the messages passed will be self-explanatory. We will talk more about this uniformity, which is called the

u

niform interface

.

As REST is an architectural style, a service can be developed using any language or platform as long as it supports HTTP.

You can read the whole dissertation at https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. 

Resource-oriented architecture

Every resource on the web has been given a unique identifier, otherwise known as a URI. The uniform resource locator (URL) is the most common type of URI used on the web today. The URLhttps://www.packtpub.com/ identifies and locates the Packt Publishing site.

Let's look at a quick picture of the architecture. In the following diagram, a client is trying to access a resource through an identifier (URL). The resource is present on the server and has a representation that can be returned to the client when requested:  

As the name suggests, the URL is something that is tied to only one resource; therefore, if I want to point someone to one resource, I can easily share that identifier in email, chat, and so on.

These identifiers can by easily remembered if they are named with company or resource names. The best example is www.google.com, which is very easy to remember as the name Google is present. Therefore, we can spread the resource link by word of mouth and you can enter it into a web browser, such as Chrome or Firefox, within seconds.

You might find hyperlinks on a particular web page that link to another website for another resource. That means that resources are now interconnected because of the hyperlinks.

These interconnected resources form the resource-oriented architecture. Hyperlinks make it easy to navigate from one resource to another by using the target resource URI.

For example, in HTML, you link to another resource through the anchor element. The following is one anchor element that links to Packt's IoT book catalog page:<a href="https://www.packtpub.com/tech/Internet%20of%20 Things">Packt IoT Books</a>

By default, the anchor element is rendered as an underlined text. When you hover over it, you can see the attached URI at the bottom, as shown in the following screenshot:

You can click on the anchor text (Packt IoT Books), which then fires a GET request for the target resource URI.

Note that the moment you click the hyperlink, you will land on a web page that is actually a representation of a resource. The most common representation you will encounter is in HTML format. Some other common formats are (X)HTML, JPEG, GIF, WMV, SWF, RSS, ATOM, CSS, JavaScript/JSON, and so on. When a browser receives one of these representations, it tries to parse it and then renders it for viewing, if parsing succeeds.

URI

We have talked a lot about resources. They are actually the pages that we see on a particular website. However, resources in HTTP are not just simple files in the form of HTML web pages. Generally, a resource is defined as any piece of information that can be uniquely  identified by a URI, such as http://packtpub.com/.

Let's talk about URIs for a moment. A URI consists of a few components: a URI scheme name, such as http or ftp is the first part, followed by a colon character. After the colon character comes the hierarchical part:

<scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ]

Let's analyze one URI:

https://www.flipkart.com/men/tshirts/pr?sid=2oq%2Cs9b%2Cj9y

Let's break down the preceding URI:

The scheme name is

https

.

The scheme name is followed by the hierarchical part, 

//www.flipkart.com/men/tshirts/pr

. The hierarchical part starts with

//

.

The hierarchical part also contains an optional query, which is

sid=2oq%2Cs9b%2Cj9y

, in this case.

The following is an example of a URI containing the optional fragment part:

https://en.wikipedia.org/wiki/Packt#PacktLib

REST constraints

REST is defined by six constraints, as shown in the following diagram. One of them is optional:

Each of these constraints enforce a design decision for the service that is to be followed. If it is not followed, the service can't be denoted as RESTful. Let's discuss these constraints one by one.

Client-server architecture

The client or the consumer of the service should not worry about how the server processes the data and stores it in the database. Similarly, the server does not need to depend on the client's implementation, especially the UI.

Think of an internet of things device or sensor that doesn't have much of a UI. However, it interacts with the server to store data using APIs, which are programmed to be fired on specific events. Suppose you are using an IoT device that alerts you when your car runs out of petrol. At the time of a petrol shortage detection by the sensor in the IoT device, it calls the configured API, which then finally sends an alert to the owner.

What that means is that the client and server are not one entity and each can live without the other. They can be designed and evolved independently. Now you might ask, How can a client work without knowing about the server's architecture, and vice versa?Well, that is what these constraints are meant for. The service, when interacted with by the clients, provides enough information about its nature: how to consume it, and what operations you can carry out using it.

As we go ahead in this section, you will realize that there is absolutely no relation between the client and the server, and they can be completely decoupled if they adhere to all these constraints perfectly. 

Stateless

The term stateless means that the state in which the application remains for a particular time may not persist to the next moment. A RESTful service does not maintain the application's state, and thus it is stateless.

A request in a RESTful service does not depend on a past request. The service treats each request independently. On the other hand, a stateful service needs to record the application's current state when the request is performed so that it can act as required for the next request.

Moreover, because of an absence of these complications, stateless services become very easy to host. As we need not worry about the state of the application, it becomes easy to implement, and maintenance becomes smooth.

Caching

To avoid generating the same data with every request, there is a technique called caching that is used to store the data either on the client's or the server's side. This cached data may be used for further reference whenever it is required.

When using caching, it is important that you manage it properly. The reason for this is simple. We are storing data that won't be replaced by fresh data from the server. While this is an advantage that increases the performance of the service, at the same time, if we are not careful as to what to cache and configure during its lifetime, we might end up seeing outdated data. For example, suppose we are showing the live price of gold on our website and we cached this figure. The next time the price changes, it won't be reflected unless we expire the cache that was previously stored.