0% found this document useful (0 votes)
119 views41 pages

UNIT-4: What Is Restful Web Services? Restful Web Services Is A Lightweight, Maintainable, and Scalable

Restful Web Services expose secure and uniform APIs from applications in a stateless manner using the underlying HTTP protocol. Key elements include resources accessed via URLs, HTTP verbs like GET and POST that describe operations on resources, and response codes. REST architectures divide applications into distributed resources that can be accessed via standard HTTP commands. Services are stateless and support caching for efficiency.

Uploaded by

mahesh babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views41 pages

UNIT-4: What Is Restful Web Services? Restful Web Services Is A Lightweight, Maintainable, and Scalable

Restful Web Services expose secure and uniform APIs from applications in a stateless manner using the underlying HTTP protocol. Key elements include resources accessed via URLs, HTTP verbs like GET and POST that describe operations on resources, and response codes. REST architectures divide applications into distributed resources that can be accessed via standard HTTP commands. Services are stateless and support caching for efficiency.

Uploaded by

mahesh babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT-4

What is Restful Web Services?


Restful Web Services is a lightweight, maintainable, and scalable
service that is built on the REST architecture. Restful Web Service,
expose API from your application in a secure, uniform, stateless manner
to the calling client. The calling client can perform predefined operations
using the Restful service. The underlying protocol for REST is HTTP.
REST stands for REpresentational State Transfer.

RESTful Key Elements


The key elements of a RESTful implementation are as follows:

1. Resources – The first key element is the resource itself. Let


assume that a web application on a server has records of several
employees. Let’s assume the URL of the web application
is http://demo.guru99.com. Now in order to access an employee
record resource via REST services, one can issue the
command http://demo.guru99.com/employee/1 – This command
tells the web server to please provide the details of the employee
whose employee number is 1.
2. Request Verbs – These describe what you want to do with the
resource. A browser issues a GET verb to instruct the endpoint it
wants to get data. However, there are many other verbs available
including things like POST, PUT, and DELETE. So in the case of
the example http://demo.guru99.com/employee/1 , the web
browser is actually issuing a GET Verb because it wants to get the
details of the employee record.
3. Request Headers – These are additional instructions sent with the
request. These might define the type of response required or the
authorization details.
4. Request Body – Data is sent with the request. Data is normally
sent in the request when a POST request is made to the REST
web services. In a POST call, the client actually tells the REST
web services that it wants to add a resource to the server. Hence,
the request body would have the details of the resource which is
required to be added to the server.
5. Response Body – This is the main body of the response. So in
our RESTful API example, if we were to query the web server via
the request http://demo.guru99.com/employee/1 , the web
server might return an XML document with all the details of the
employee in the Response Body.
6. Response Status codes – These codes are the general codes
which are returned along with the response from the web server.
An example is the code 200 which is normally returned if there is
no error when returning a response to the client.

Restful Methods
The below diagram shows mostly all the verbs (POST, GET, PUT, and
DELETE) and an REST API example of what they would mean.

Let’s assume that we have a RESTful web service is defined at the


location. http://demo.guru99.com/employee . When the client makes
any request to this web service, it can specify any of the normal HTTP
verbs of GET, POST, DELETE and PUT. Below is what would happen If
the respective verbs were sent by the client.

1. POST – This would be used to create a new employee using the


RESTful web service
2. GET – This would be used to get a list of all employee using the
RESTful web service
3. PUT – This would be used to update all employee using the
RESTful web service
4. DELETE – This would be used to delete all employee using the
RESTful services

The following actions would have their respective meanings.

1. POST – This would not be applicable since we are fetching data of


employee 1 which is already created.
2. GET – This would be used to get the details of the employee with
Employee no as 1 using the RESTful web service
3. PUT – This would be used to update the details of the employee
with Employee no as 1 using the RESTful web service
4. DELETE – This is used to delete the details of the employee with
Employee no as 1

Why Restful
Restful mostly came into popularity due to the following reasons:
1. Heterogeneous languages and environments – This is one of the
fundamental reasons which is the same as we have seen for SOAP as
well.

 It enables web applications that are built on various programming


languages to communicate with each other
 With the help of Restful services, these web applications can
reside on different environments, some could be on Windows, and
others could be on Linux.
 Facebook, Twitter, and Google expose their functionality in the
form of Restful web services. This allows any client application to
call these web services via Rest.

2. The event of Devices – Nowadays, everything needs to work


on Mobile devices, whether it be the mobile device, the notebooks, or
even car systems.

Can you imagine the amount of effort to try and code applications on
these devices to talk with normal web applications? Again Restful API’s
can make this job simpler because as mentioned in point no 1, you really
don’t need to know what is the underlying layer for the device.

3. Finally is the event of the Cloud – Everything is moving to the cloud.


Applications are slowly moving to cloud-based systems such as in Azure
or Amazon. Azure and Amazon provide a lot of API’s based on the
Restful architecture. Hence, applications now need to be developed in
such a way that they are made compatible with the Cloud. So since all
Cloud-based architectures work on the REST principle, it makes more
sense for web services to be programmed on the REST services based
architecture to make the best use of Cloud-based services.

Restful Architecture
An application or architecture considered RESTful or REST-style has the
following characteristics

1. State and functionality are divided into distributed resources –


This means that every resource should be accessible via the normal
HTTP commands of GET, POST, PUT, or DELETE. So if someone
wanted to get a file from a server, they should be able to issue the GET
request and get the file. If they want to put a file on the server, they
should be able to either issue the POST or PUT request. And finally, if
they wanted to delete a file from the server, they an issue the DELETE
request.

2. The architecture is client/server, stateless, layered, and supports


caching

 Client-server is the typical architecture where the server can be the


web server hosting the application, and the client can be as simple
as the web browser.
 Stateless means that the state of the application is not maintained
in REST.For example, if you delete a resource from a server using
the DELETE command, you cannot expect that delete information
to be passed to the next request.

RESTFul Principles and Constraints


The REST architecture is based on a few characteristics which are
elaborated below. Any RESTful web service has to comply with the
below characteristics in order for it to be called RESTful. These
characteristics are also known as design principles which need to be
followed when working with RESTful based services.

1. RESTFul Client-Server

This is the most fundamental requirement of a REST based architecture.


It means that the server will have a RESTful web service which would
provide the required functionality to the client. The client send’s a
request to the web service on the server. The server would either reject
the request or comply and provide an adequate response to the client.

2. Stateless

The concept of stateless means that it’s up to the client to ensure that all
the required information is provided to the server. This is required so that
server can process the response appropriately. The server should not
maintain any sort of information between requests from the client. It’s a
very simple independent question-answer sequence. The client asks a
question, the server answers it appropriately. The client will ask another
question. The server will not remember the previous question-answer
scenario and will need to answer the new question independently.

3. Cache
The Cache concept is to help with the problem of stateless which was
described in the last point. Since each server client request is
independent in nature, sometimes the client might ask the server for the
same request again. This is even though it had already asked for it in the
past. This request will go to the server, and the server will give a
response. This increases the traffic across the network. The cache is a
concept implemented on the client to store requests which have already
been sent to the server. So if the same request is given by the client,
instead of going to the server, it would go to the cache and get the
required information. This saves the amount of to and fro network traffic
from the client to the server.

4. Layered System

The concept of a layered system is that any additional layer such as a


middleware layer can be inserted between the client and the actual
server hosting the RESTFul web service (The middleware layer is where
all the business logic is created. This can be an extra service created
with which the client could interact with before it makes a call to the web
service.). But the introduction of this layer needs to be transparent so
that it does not disturb the interaction between the client and the server.

5. Interface/Uniform Contract

This is the underlying technique of how RESTful web services should


work. RESTful basically works on the HTTP web layer and uses the
below key verbs to work with resources on the server

 POST – To create a resource on the server


 GET – To retrieve a resource from the server
 PUT – To change the state of a resource or to update it
 DELETE – To remove or delete a resource from the server

Create your first Restful web service in ASP.NET


Now in this REST API tutorial, we will learn how to create a Restful web
service in ASP.NET:

Web services can be created in a variety of languages. Many integrated


development environments can be used to create REST-based services.

In this RESTful API example, we are going to create our REST


application in .Net using Visual Studio. In our example, for Restful web
services we are going to emulate the following REST service example.
We are going to have a Restful web service which will work on the below
set of data.

The below set of data represents an REST API example of having a


company which exposes the Tutorial’s they have based on the Tutorialid.

Tutorialid TutorialName
0 Arrays
1 Queues
2 Stacks
In our REST API tutorial example, we are going to implement the below
Restful Verbs.

1. GET Tutorial – When a client invokes this Restful API, they will be
given the entire set of Tutorials available from the web service.
2. GET Tutorial/Tutorialid – When a client invokes this Restful API,
they will be given the Tutorial name based on the Tutorialid sent by
the client.
3. POST Tutorial/Tutorialname – When a client invokes this Restful
API, the client will submit a request to insert a Tutorialname. The
web service will then add the submitted Tutorial name to the
collection.
4. DELETE Tutorial/Tutorialid– When a client invokes this Restful
API, the client will submit a request to delete a Tutorialname based
on the Tutorialid. The web service will then delete the submitted
Tutorial name from the collection.

Using the Uniform Interface

HTTP is an application-level protocol that defines operations for


transferring representations between clients and servers. In this protocol,
methods such as GET, POST, PUT, and DELETE are operations on
resources. This protocol eliminates the need for you to invent
application-specific operations such
as createOrder, getStatus, updateStatus, etc. How much you can benefit
from the HTTP infrastructure largely depends on how well you can use
HTTP as an application-level protocol. However, a number of techniques
including SOAP and some Ajax web frameworks use HTTP as a protocol
to transport messages. Such usage makes poor use of HTTP-level
infrastructure. This chapter presents the following recipes to highlight
various aspects of using HTTP as an application protocol:
Recipe 1.1

Visibility is one of the key characteristics of HTTP. Use this recipe


to learn how to maintain visibility.

Recipe 1.2

There are cases when you may need to forgo visibility to meet
application needs. Use this recipe to find some scenarios.

Recipe 1.3

Use this recipe to learn the best way to manage state.

Recipe 1.4

Maintaining safety and idempotency helps servers guarantee


repeatability for requests. Use this recipe when implementing
servers.

Recipe 1.5

Follow this recipe to implement clients for safety and idempotency


principles.

Recipe 1.6

Use this recipe to learn when to use GET.


Recipe 1.7

Use this recipe to learn when to use POST.


Recipe 1.8

Use this recipe to learn how to create new resources using


the POST method.
Recipe 1.9
You can use either POST or PUT to create new resources. This
recipe will discuss when using PUT is better.
Recipe 1.10

Use this recipe to learn how to use the POST method for


asynchronous tasks.
Recipe 1.11

Use this recipe to learn how to use the DELETE method for


asynchronous deletion of resources.
Recipe 1.12

Use this recipe to learn why custom HTTP methods are not
recommended.

Recipe 1.13

Use this recipe to learn when and how to use custom HTTP
headers.

HTTP achieves visibility by virtue of the following:

 HTTP interactions are stateless. Any HTTP intermediary can infer


the meaning of any given request and response without correlating them
with past or future requests and responses.
 HTTP uses a uniform interface consisting
of OPTIONS, GET, HEAD, POST, PUT, DELETE, and TRACE methods.
Each method in this interface operates on one and only one resource.
The syntax and the meaning of each method do not change from
application to application or from resource to resource. That is why
HTTP is known as a uniform interface.

 HTTP uses a MIME-like envelope format to encode


representations. This format maintains a clear separation between
headers and the body. Headers are visible, and except for the software
that is creating the message and the software that is processing the
message, every piece of software in between can treat the body as
completely opaque.
URL design

 URLs always need to be clear, unambiguous, easy to read, easy to


type and easy to share
 all URLs must be in lower case
 URLs must use words and should not contain acronyms, wherever
possible (see 8 for an exception where acronyms are used for an
organisation redirect)
 dashes should be used to separate words within URLs so they are
easy to read, e.g. https://www.mygov.scot/running-a-limited-
company/ (see 5, 7 and 15 for exceptions on campaign landing
pages and service sub-domain URLs)
 articles (a, an, the) and other superfluous words should not be used,
e.g. use /benefits/ or /benefits-guides/ rather than /a-guide-to-
benefits/
 URLs should use the verb stem, where possible, e.g. /apply/ instead
of /applying/
 each page must have a URL which is as short, memorable and
unambiguous as possible, especially if a URL is going to be referred
to offline
 URLs should be based on user need rather than the (current) name
of a policy, scheme or service, which might change, e.g. the
URL https://www.mygov.scot/help-with-childcare-costs/ is intended
for people who wish to seek help with covering the costs of caring
for their children.

General principles for good URI desin:

 Don’t use query parameters to alter state

 Don’t use mixed-case paths.Lowercase is best

 Don’t use implementation-specific extensions in your URIs


(.php, .py, .pl, etc.)

 Do keep path segments short


 Do use query parameters for sub-selection of a resource; i.e.
pagination, search queries

 Do move stuff out of the URI that should be in an HTTP header or a


body

 Use plural names for all resources.


Web Linking

Web Linking (RFC 8288 which obsoleted RFC 5988) define a means of


indicating the relationships between resources on the Web, as well as
indicating the type of those relationships, has been available for some
time in HTML W3C.REC-html401-19991224, and more recently
in Atom RFC 4287.

These mechanisms, although conceptually similar, are separately


specified. However, links between resources need not be format
specific; it can be useful to have typed links that are independent of their
serialization, especially when a resource has representations in multiple
formats.
To this end, RFC 8288 defines a framework for typed links that isn't
specific to a particular serialization or application. RFC 8288 does so by
redefining the link relation established by Atom to have a broader
domain, and adding to it the relations that are defined by HTML.
Furthermore, an HTTP Header Field for conveying typed links was
defined in Section 19.6.2.4 of RFC 2068, but removed from RFC 2616,
due to a lack of implementation experience. Since then, it has been
implemented in some User-agents (e.g., for style-sheets), and several
additional use cases have surfaced.
Because it was removed, the status of the Link header is unclear,
leading some to consider minting new application-specific HTTP Header
Field instead of reusing it. RFC 8288 addresses this by re-specifying the
Link header as one such serialization, with updated but backwards-
compatible syntax.
Web Linking (RFC 8288) specification establishes the Link Relation
Types IANA Registry, and updates Atom RFC 4287 to refer to it in place
of the "Registry of Link Relations".
Links#
Web Linking (RFC 5988), a link is a typed connection between
two resources that are identified by Internationalized Resource
Identifiers (IRIs) RFC 3987, and is comprised of:

 A context IRI,
 a Link Relation Type,
 a target IRI,
 optionally, target attributes.

A link can be viewed as a statement of the form "{context IRI} has a


{relation type} resource at {target IRI}, which has {target attributes}".
Note that in the common case, the context IRI will also be a URI RFC
3986, because many protocols (such as HTTP) do not support
dereferencing IRIs. Likewise, the target IRI will be converted to
a URI (see RFC 3987, Section 3.1) in serialisations that do not support
IRIs (e.g., the Link header).
HTTP conditional requests
HTTP has a concept of conditional requests, where the result, and even
the success of a request, can be changed by comparing the affected
resources with the value of a validator. Such requests can be useful to
validate the content of a cache, and sparing a useless control, to verify
the integrity of a document, like when resuming a download, or when
preventing lose updates when uploading or modifying a document on the
server.

Principles
HTTP conditional requests are requests that are executed differently,
depending on the value of specific headers. These headers define a
precondition, and the result of the request will be different if the
precondition is matched or not.

The different behaviors are defined by the method of the request used,
and by the set of headers used for a precondition:

 for safe methods, like GET, which usually tries to fetch a document,


the conditional request can be used to send back the document, if
relevant only. Therefore, this spares bandwidth.
 for unsafe methods, like PUT, which usually uploads a document,
the conditional request can be used to upload the document, only if
the original it is based on is the same as that stored on the server.
Validators
All conditional headers try to check if the resource stored on the server
matches a specific version. To achieve this, the conditional requests
need to indicate the version of the resource. As comparing the whole
resource byte to byte is impracticable, and not always what is wanted,
the request transmits a value describing the version. Such values are
called validators, and are of two kinds:

 the date of last modification of the document, the last-


modified date.
 an opaque string, uniquely identifying each version, called
the entity tag, or the etag.
Comparing versions of the same resource is a bit tricky: depending
on the context, there are two kinds of equality checks:

 Strong validation is used when byte to byte identity is expected, for


example when resuming a download.
 Weak validation is used when the user-agent only needs to
determine if the two resources have the same content. This is even
if they are minor differences; like different ads, or a footer with a
different date.
The kind of validation is independent of the validator used. Both Last-
Modified and ETag allow both types of validation, though the complexity
to implement it on the server side may vary. HTTP uses strong validation
by default, and it specifies when weak validation can be used.

Strong validation
Strong validation consists of guaranteeing that the resource is, byte to
byte, identical to the one it is compared to. This is mandatory for some
conditional headers, and the default for the others. Strong validation is
very strict and may be difficult to guarantee at the server level, but it does
guarantee no data loss at any time, sometimes at the expense of
performance.
It is quite difficult to have a unique identifier for strong validation
with Last-Modified. Often this is done using an ETag with the MD5 hash
of the resource (or a derivative).

Weak validation
Weak validation differs from strong validation, as it considers two
versions of the document as identical if the content is equivalent. For
example, a page that would differ from another only by a different date in
its footer, or different advertising, would be considered identical to the
other with weak validation. These same two versions are
considered different when using strong validation. Building a system of
etags that creates weak validation may be complex, as it involves
knowing the importance of the different elements of a page, but is very
useful towards optimizing cache performance.

Conditional headers
Several HTTP headers, called conditional headers, lead to conditional
requests. These are:

If-Match

Succeeds if the ETag of the distant resource is equal to one


listed in this header. By default, unless the etag is prefixed
with 'W/', it performs a strong validation.

If-None-Match

Succeeds if the ETag of the distant resource is different to each


listed in this header. By default, unless the etag is prefixed
with 'W/', it performs a strong validation.

If-Modified-Since

Succeeds if the Last-Modified date of the distant resource is


more recent than the one given in this header.

If-Unmodified-Since

Succeeds if the Last-Modified date of the distant resource is


older or the same as the one given in this header.

If-Range
Similar to If-Match, or If-Unmodified-Since, but can have only
one single etag, or one date. If it fails, the range request fails,
and instead of a 206 Partial Content response, a 200 OK is sent
with the complete resource.

Use cases
Cache update
The most common use case for conditional requests is updating a cache.
With an empty cache, or without a cache, the requested resource is sent
back with a status of 200 OK.

Together with the resource, the validators are sent in the headers. In this
example, both Last-Modified and ETag are sent, but it could equally have
been only one of them. These validators are cached with the resource
(like all headers) and will be used to craft conditional requests, once the
cache becomes stale.

As long as the cache is not stale, no requests are issued at all. But once
it has become stale, this is mostly controlled by the Cache-
Control header, the client doesn't use the cached value directly but
issues a conditional request. The value of the validator is used as a
parameter of the If-Modified-Since and If-Match headers.

If the resource has not changed, the server sends back a 304 Not
Modified response. This makes the cache fresh again, and the client
uses the cached resource. Although there is a response/request round-
trip that consumes some resources, this is more efficient than to transmit
the whole resource over the wire again.
If the resource has changed, the server just sends back a 200
OK response, with the new version of the resource, like if the request
wasn't conditional and the client uses this new resource (and caches it).

ReactJS

ReactJS tutorial provides basic and advanced concepts of ReactJS.


Currently, ReactJS is one of the most popular JavaScript front-end
libraries which has a strong foundation and a large community.

ReactJS is a declarative, efficient, and flexible JavaScript library for


building reusable UI components. It is an open-source, component-
based front end library which is responsible only for the view layer of the
application. It was initially developed and maintained by Facebook and
later used in its products like WhatsApp & Instagram.
Our ReactJS tutorial includes all the topics which help to learn ReactJS.
These are ReactJS Introduction, ReactJS Features, ReactJS
Installation, Pros and Cons of ReactJS, ReactJS JSX, ReactJS
Components, ReactJS State, ReactJS Props, ReactJS Forms, ReactJS
Events, ReactJS Animation and many more.

Why we use ReactJS?

The main objective of ReactJS is to develop User Interfaces (UI) that


improves the speed of the apps. It uses virtual DOM (JavaScript object),
which improves the performance of the app. The JavaScript virtual DOM
is faster than the regular DOM. We can use ReactJS on the client and
server-side as well as with other frameworks. It uses component and
data patterns that improve readability and helps to maintain larger apps.

Pros and Cons of ReactJS

Today, ReactJS is the highly used open-source JavaScript Library. It


helps in creating impressive web apps that require minimal effort and
coding. The main objective of ReactJS is to develop User Interfaces (UI)
that improves the speed of the apps. There are important pros and cons
of ReactJS given as following:

Advantage of ReactJS

1. Easy to Learn and USe

ReactJS is much easier to learn and use. It comes with a good supply of
documentation, tutorials, and training resources. Any developer who
comes from a JavaScript background can easily understand and start
creating web apps using React in a few days. It is the V(view part) in the
MVC (Model-View-Controller) model, and referred to as ?one of the
JavaScript frameworks.? It is not fully featured but has the advantage of
open-source JavaScript User Interface(UI) library, which helps to
execute the task in a better manner.

2. Creating Dynamic Web Applications Becomes Easier

History of Java

To create a dynamic web application specifically with HTML strings was


tricky because it requires a complex coding, but React JS solved that
issue and makes it easier. It provides less coding and gives more
functionality. It makes use of the JSX(JavaScript Extension), which is a
particular syntax letting HTML quotes and HTML tag syntax to render
particular subcomponents. It also supports the building of machine-
readable codes.

3. Reusable Components

A ReactJS web application is made up of multiple components, and


each component has its own logic and controls. These components are
responsible for outputting a small, reusable piece of HTML code which
can be reused wherever you need them. The reusable code helps to
make your apps easier to develop and maintain. These Components can
be nested with other components to allow complex applications to be
built of simple building blocks. ReactJS uses virtual DOM based
mechanism to fill data in HTML DOM. The virtual DOM works fast as it
only changes individual DOM elements instead of reloading complete
DOM every time.

4. Performance Enhancement

ReactJS improves performance due to virtual DOM. The DOM is a


cross-platform and programming API which deals with HTML, XML or
XHTML. Most of the developers faced the problem when the DOM was
updated, which slowed down the performance of the application.
ReactJS solved this problem by introducing virtual DOM. The React
Virtual DOM exists entirely in memory and is a representation of the web
browser's DOM. Due to this, when we write a React component, we did
not write directly to the DOM. Instead, we are writing virtual components
that react will turn into the DOM, leading to smoother and faster
performance.

5. The Support of Handy Tools

React JS has also gained popularity due to the presence of a handy set
of tools. These tools make the task of the developers understandable
and easier. The React Developer Tools have been designed as Chrome
and Firefox dev extension and allow you to inspect the React component
hierarchies in the virtual DOM. It also allows you to select particular
components and examine and edit their current props and state.

6. Known to be SEO Friendly

Traditional JavaScript frameworks have an issue in dealing with SEO.


The search engines generally having trouble in reading JavaScript-
heavy applications. Many web developers have often complained about
this problem. ReactJS overcomes this problem that helps developers to
be easily navigated on various search engines. It is because React.js
applications can run on the server, and the virtual DOM will be rendering
and returning to the browser as a regular web page.

7. The Benefit of Having JavaScript Library

Today, ReactJS is choosing by most of the web developers. It is


because it is offering a very rich JavaScript library. The JavaScript library
provides more flexibility to the web developers to choose the way they
want.

8. Scope for Testing the Codes

ReactJS applications are extremely easy to test. It offers a scope where


the developer can test and debug their codes with the help of native
tools.

Disadvantage of ReactJS

1. The high pace of development

The high pace of development has an advantage and disadvantage


both. In case of disadvantage, since the environment continually
changes so fast, some of the developers not feeling comfortable to
relearn the new ways of doing things regularly. It may be hard for them
to adopt all these changes with all the continuous updates. They need to
be always updated with their skills and learn new ways of doing things.

2. Poor Documentation

It is another cons which are common for constantly updating


technologies. React technologies updating and accelerating so fast that
there is no time to make proper documentation. To overcome this,
developers write instructions on their own with the evolving of new
releases and tools in their current projects.

3. View Part

ReactJS Covers only the UI Layers of the app and nothing else. So you
still need to choose some other technologies to get a complete tooling
set for development in the project.

4. JSX as a barrier
ReactJS uses JSX. It's a syntax extension that allows HTML with
JavaScript mixed together. This approach has its own benefits, but some
members of the development community consider JSX as a barrier,
especially for new developers. Developers complain about its complexity
in the learning curve.

React Features:

Currently, ReactJS gaining quick popularity as the best JavaScript


framework among web developers. It is playing an essential role in the
front-end ecosystem. The important features of ReactJS are as
following.

o JSX
o Components
o One-way Data Binding
o Virtual DOM
o Simplicity
o Performance

Future of ReactJS
ReactJS is a declarative, versatile JavaScript framework for building
customizable user interfaces ( UI) with greater simplicity and usability.
An application for various states provides some benefits in generating
basic views and greater convenience in quickly changing and rendering
the related components just as data changes.
React.js is a vital part of the above group and not just a coming and
going system. Released in 2013, the list of the most creative innovations
continues to grow.
Facebook-developed React is an open-source JavaScript framework
that works well for user interface design. Developers use React de to
create interchangeable UI modules and manage display layers for
network and mobile applications. The React development also utilizes
synthetic DOM, the JavaScript object. It increases the efficiency of apps
since the DOM of JS is quicker than the standard one.
In modern JavaScript creation, React.js is one of the most
developmentally important frontend libraries you can use. It helps you to
create highly reactive user interfaces that have a user experience that is
fast and mobile-app-like.
As a developer, you concentrate on creating modules in a declarative
fashion while operating with React (i.e., you decide how it should look,
not how it should get there), and React will take care of the rest. You can
rely on its quick and streamlined internal rendering process and thus
have an excellent experience for your users.
With minimal code, it is primarily intended to quickly and reliably create
rich and engaging mobile applications.
Instead of a full web app, React JS gives the ability to function on
individual components, which allows them to have the best possible
rendering output.
React development has emerged as the future of web creation with its
extra versatility and ease. Issues linked.
Over 94000 pages are estimated to use ReactJS, and more than 1300
developers are actively using ReactJS for development.
Facebook, PayPal, Instagram, Uber, and Airbnb are the most famous
examples of the use of ReactJS.
In web development, new frameworks are starting to be built to resolve
the libraries' limitations or frameworks before them. ReactJS has
overcome many of the shortcomings of prior implementations like
AngularJS. It is used to develop fast and scalable web applications, and
new plugins are designed for ReactJS as soon as the need for additional
functionality increases.
ReactJS developers have a bright future ahead as the technology is in
use in several industries. In fact, as opposed to other Web development
technology, React developers are now paying the most.
If you have an in-depth knowledge of JavaScript and even HTML5 to
work with React, it will help. JS, which would be beneficial, which is
similar when dealing with JSX.
You will be able to function both on the client-side and the server-side. It
will facilitate the development of larger applications with its portion and
data patterns that improve readability.
Thanks to its versatility, increased performance, and improved usability
features, it is an outstanding frontend development program.
Facebook and the whole ReactJS team have shown the commitment to
improving the efficiency of ReactJS. This is important for the increasingly
emerging competition from other systems such as Vue.js to be resolved.
Any of the considerations to remember are server-side rendering
extension in upcoming releases. A redesigned server rendering comes
with the latest ReactJS that makes it very fast and streamable. It's a
great spot to refine the presentation.
Developers also await a rise in the handling of errors. In the past, during
rendering, runtime errors sometimes put ReactJS in an awkward, broken
state. This also involves refreshing the page. The established model of
resolving the error is thrown inside the part or lifecycle processes.
Although this helps avoid the corrupt rendering of results, the improved
UX is not the right idea.
ReactJS experts should expect fresh ways of rendering. For starters, the
ReactJS team is likely to add a special fragment syntax to the JSX that
needs no keys.
Learning the development of "ReactJS" makes perfect sense because it
provides developers with much-needed simplicity in considerably less
time to produce highly immersive mobile apps and user interfaces. They
design large-scale applications with continuously evolving data. The
advantages of being modular, scalable, agile, non-risky, user-friendly
greatly outweigh the disadvantages of developers and organizations.
React is easy to use for programmers, ensuring businesses are
effectively deploying their projects and being more profitable. The
platform of React.js revolutionizes the way the frontend is handled. By
offering a View UI and a storage layer, it addresses the view issue. It will
connect to an API-like backend that uses routers, controllers, and
templates to access data and execute backend logic.
It was ingenious for Facebook to create a framework for UI rendering; it
is simple, easy to get used to, and instrumental. React resolves the
display problem by building a UI and a data layer on the Display. It will
use routers, controllers, and models to communicate with an API-like
backend that accesses data and implements back-end logic.
Developers write programs to React in terms of "Components." And if it's
too intricate a component, don't worry. We're going to break it up into
smaller, more manageable, reusable pieces!
Working with the files:

File uploading in React.js


For any developer who envisions building an application, uploading
images is a major component they have to take into account. It is an
essential requirement while creating a complete application. File
uploading means a user from a client machine wants to upload files to
the server. For example, users can upload images, videos, etc on
Facebook, Instagram. As with any programming problem, there are
many ways to achieve this outcome. This article explains a simple way
to implement the approach to upload a single file with React.

The process of uploading an image can be broadly divided into two


steps:

 Select a File (user input): To enable the user to pick a file, the
first step is to add the tag to our App component. This tag should
have the type attribute set as “file”. Now, we need an event
handler to listen to any changes made to the file. This event
handler will be triggered whenever the user selects a new file and
will update the state.
 Send a request to the server: After storing the selected file (in
the state), we are now required to send it to a server. For this
purpose, we can use fetch or Axios. (In this code, we use Axios a
promise-based HTTP client for the browser and NodeJS). The file
is sent to the service wrapped in a FormData object.
ReactJS Pure Components
Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle
method to customize the default behavior and implement it when the
React component should re-render or update itself.
Prerequisite: 
 ReactJS Components
 ReactJS Components – Set 2
 
 
Now, ReactJS has provided us a Pure Component. If we extend a
class with Pure Component, there is no need
for shouldComponentUpdate() Lifecycle Method. ReactJS Pure
Component Class compares current state and props with new props
and states to decide whether the React component should re-render
itself or  Not.
In simple words, If the previous value of state or props and the new
value of state or props is the same, the component will not re-render
itself. Since Pure Components restricts the re-rendering when there is
no use of re-rendering of the component. Pure Components are Class
Components which extends React.PureComponent.
Example:  Program to demonstrate the creation of Pure Components. 

javascript

import React from ‘react’;

export default class Test extends React.PureComponent{

   render(){

      return <h1>Welcome to GeeksforGeeks</h1>;

   }
}

Output :

Extending React Class Components with Pure Components ensures


the higher performance of the Component and ultimately makes your
application faster, While in the case of Regular Component, it will
always re-render either value of State and Props changes or not.
While using Pure Components, Things to be noted are that, In these
components, the Value of State and Props are Shallow
Compared (Shallow Comparison) and It also takes care of
“shouldComponentUpdate” Lifecycle method implicitly.
So there is a possibility that if these State and Props Objects contain
nested data structure then Pure Component’s
implemented shouldComponentUpdate will return false and will not
update the whole subtree of Children of this Class Component. So
in Pure Component, the nested data structure doesn’t work properly.
In this case, State and Props Objects should be simple objects and
Child Elements should also be Pure, means to return the same output
for the same input values at any instance.
Page setup:

78
51
I have created a single page web app using react js. I have
used webpack to create bundle of all components. But now I want to
create many other pages. Most of pages are API call related. i.e. in
the index.html, I have displayed content from API. I want to insert
content in another page parsing data from API. Webpack compresses
everything of react in a file which is bundle.js. However, the configuration
of webpack is as follow:

const webpack = require('webpack');


var config = {
entry: './main.js',

output: {
path:'./',
filename: 'dist/bundle.js',
},

devServer: {
inline: true,
port: 3000
},

module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',

query: {
presets: ['es2015', 'react']
}
}
]
},

plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
Virtual DOM
DOM: DOM stands for ‘Document Object Model’. In simple terms, it is a
structured representation of the HTML elements that are present in a
webpage or web-app. DOM represents the entire UI of your application.
The DOM is represented as a tree data structure. It contains a node for
each UI element present in the web document. It is very useful as it
allows web developers to modify content through JavaScript, also it
being in structured format helps a lot as we can choose specific targets
and all the code becomes much easier to work with. If you want to learn
more about DOM, visit this link.
Updating DOM: If you know a little about JavaScript then you might
have seen people making use of ‘getElementById()’ or
‘getElementByClass()’ method to modify the content of DOM. Every
time there is a change in the state of your application, the DOM get’s
updated to reflect that change in the UI. Though doing things like this is
not a problem and it works fine, but consider a case where we have a
DOM that contains nodes in a large number, and also all these web
elements have different styling and attributes.  As DOM is represented
as a tree itself, updating the tree here is not a costly operation indeed
we have a lot of algorithms on trees to make the updates fast. What’s
proving to be costly is everytime the DOM gets updated, the updated
element and it’s children have to be rendered again to update the UI of
our page. Like this each time there is a component update, the DOM
needs to be updated and the UI components have to be re-rendered.
Example: 
javascript

// Simple getElementById() method

document.getElementById('some-id').innerValue = 'updated value';

When writing the above code in the console or in the JavaScript file,
these things happen: 
 The browser parses the HTML to find the node with this id.
 It removes the child element of this specific element.
 Updates the element(DOM) with the ‘updated value’.
 Recalculates the CSS for the parent and child nodes.
 Update the layout.
 Finally, traverse the tree and paint it on the screen(browser) display.
So as we know now that updating the DOM not only involves changing
the content, it has a lot more attached to it. Also recalculating the CSS
and changing the layouts involves complex algorithms, and they do
affect the performance. So React has a different approach to dealing
with this, as it makes use of something known as Virtual DOM.
 
Virtual DOM: React uses Virtual DOM exists which is like a lightweight
copy of the actual DOM(a virtual representation of the DOM). So for
every object that exists in the original DOM, there is an object for that in
React Virtual DOM. It is exactly the same, but it does not have the
power to directly change the layout of the document. Manipulating DOM
is slow, but manipulating Virtual DOM is fast as nothing gets drawn on
the screen. So each time there is a change in the state of our
application, virtual DOM gets updated first instead of the real DOM.
You may still wonder, “Aren’t we doing the same thing again and
doubling our work? How can this be faster?” Read below to understand
how things will be faster using virtual DOM.

How Virtual DOM actually make the things faster: When anything


new is added to the application, a virtual DOM is created and it is
represented as a tree. Each element in the application is a node in this
tree. So, whenever there is a change in state of any element, a new
Virtual DOM tree is created. This new Virtual DOM tree is then
compared with the previous Virtual DOM tree and make a note of the
changes. After this, it finds the best possible ways to make these
changes to the real DOM. Now only the updated elements will get
rendered on the page again.
How Virtual DOM helps React: In react, everything is treated as a
component be it a functional component or class component. A
component can contain a state. Each time we change something in our
JSX file or let’s put it in simple terms, whenever the state of any
component is changed react updates it’s Virtual DOM tree. Though it
may sound that it is ineffective but the cost is not much significant as
updating the virtual DOM doesn’t take much time. React maintains two
Virtual DOM at each time, one contains the updated Virtual DOM and
one which is just the pre-update version of this updated Virtual DOM.
Now it compares the pre-update version with the updated Virtual DOM
and figures out what exactly has changed in the DOM like which
components have been changed. This process of comparing the
current Virtual DOM tree with the previous one is known as ‘diffing’.
Once React finds out what exactly has changed then it updated those
objects only, on real DOM. React uses something called as batch
updates to update the real DOM. It just mean that the changes to the
real DOM are sent in batches instead of sending any update for a
single change in the state of a component. We have seen that the re-
rendering of the UI is the most expensive part and React manages to
do this most efficiently by ensuring that the Real DOM receives batch
updates to re-render the UI. This entire proces of transforming changes
to the real DOM is called Reconciliation
This significantly improves the performance and is the main reason why
React and it’s Virtual DOM is much loved by developers all around.
React DOM:
If you load React from a <script> tag, these top-level APIs are available
on the ReactDOM global. If you use ES6 with npm, you can write import
ReactDOM from 'react-dom'. If you use ES5 with npm, you can write var
ReactDOM = require('react-dom').
he react-dom package provides DOM-specific methods that can be used
at the top level of your app and as an escape hatch to get outside of the
React model if you need to. Most of your components should not need to
use this module.
 render()
 hydrate()
 unmountComponentAtNode()
 findDOMNode()
 createPortal()
render()
ReactDOM.render(element,container[ ,callback])

Render a React element into the DOM in the supplied container and


return a reference to the component (or returns null for stateless
components).
If the React element was previously rendered into container, this will
perform an update on it and only mutate the DOM as necessary to
reflect the latest React element.

If the optional callback is provided, it will be executed after the


component is rendered or updated.
hydrate()

ReactDOM.hydrate(element,container[ ,callback])

Same as render(), but is used to hydrate a container whose HTML


contents were rendered by ReactDOMServer. React will attempt to
attach event listeners to the existing markup.

React expects that the rendered content is identical between the server
and the client. It can patch up differences in text content, but you should
treat mismatches as bugs and fix them. In development mode, React
warns about mismatches during hydration. There are no guarantees that
attribute differences will be patched up in case of mismatches. This is
important for performance reasons because in most apps, mismatches
are rare, and so validating all markup would be prohibitively expensive.
If a single element’s attribute or text content is unavoidably different
between the server and the client (for example, a timestamp), you may
silence the warning by adding suppressHydrationWarning={true} to the
element. It only works one level deep, and is intended to be an escape
hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt
to patch it up, so it may remain inconsistent until future updates.
If you intentionally need to render something different on the server and
the client, you can do a two-pass rendering. Components that render
something different on the client can read a state variable
like this.state.isClient, which you can set
to true in componentDidMount(). This way the initial render pass will
render the same content as the server, avoiding mismatches, but an
additional pass will happen synchronously right after hydration. Note that
this approach will make your components slower because they have to
render twice, so use it with caution.

Remember to be mindful of user experience on slow connections. The


JavaScript code may load significantly later than the initial HTML render,
so if you render something different in the client-only pass, the transition
can be jarring. However, if executed well, it may be beneficial to render a
“shell” of the application on the server, and only show some of the extra
widgets on the client. To learn how to do this without getting the markup
mismatch issues, refer to the explanation in the previous paragraph.

unmountComponentAtNode()
ReactDOM.unmountComponentAtNode(container)

Remove a mounted React component from the DOM and clean up its
event handlers and state. If no component was mounted in the
container, calling this function does nothing. Returns true if a component
was unmounted and false if there was no component to unmount.

findDOMNode()
ReactDOM.findDOMNode(component)

If this component has been mounted into the DOM, this returns the
corresponding native browser DOM element. This method is useful for
reading values out of the DOM, such as form field values and performing
DOM measurements. In most cases, you can attach a ref to the DOM
node and avoid using findDOMNode at all.
When a component renders to null or false, findDOMNode returns null.
When a component renders to a string, findDOMNode returns a text
DOM node containing that value. As of React 16, a component may
return a fragment with multiple children, in which case findDOMNode will
return the DOM node corresponding to the first non-empty child.
createPortal()
ReactDOM.createPortal(child,container)

Creates a portal. Portals provide a way to render children into a DOM


node that exists outside the hierarchy of the DOM component.

Constructing Elements with Data:

Data elements describe the individual fields in the ABAP Data


Dictionary. They are the smallest indivisible units of the complex types,
and they are used to define the type of table field, structure component
or row type of a table. Information about the meaning of a table field
and also information about editing the corresponding screen field could
be assigned to a data element. This information is automatically
available to all the screen fields that refer to the data element. Data
elements describe either elementary types or reference types.

Creating Data Elements:


Before creating a new data element, you need to check whether any
existing data elements have the same semantic specifications required
in your table field. If so, you may use that existing data element. You
can assign the data element with a predefined type, domain, or
reference type.
Following is the procedure for creating the data element −
Step 1 − Go to Transaction SE11.
Step 2 − Select the radio button for Data type in the initial screen of the
ABAP Dictionary, and enter the name of the data element as shown
below.
Step 3 − Click the CREATE button. You may create data elements
under the customer namespaces, and the name of the object always
starts with ‘Z’ or ‘Y’.

Step 4 − Check the Data element radio button on the CREATE TYPE
pop-up that appears with three radio buttons.
Step 5 − Click the green checkmark icon. You are directed to
the maintenance screen of the data element.
Step 6 − Enter the description in the short text field of the
maintenance screen of the data element. In this case, it is
“Customer Data Element”. Note − You cannot enter any other
attribute until you have entered this attribute.

Step 7 − Assign the data element with the type. You can create an
elementary data element by checking elementary type or a reference
data element by checking Reference type. You can assign a data
element to a Domain or Predefined Type within Elementary Type and
with Name of Reference Type or Reference to Predefined Type within
Reference Type.
Step 8 − Enter the fields for short text, medium text, long text, and
heading in the Field Label tab. You can press Enter and the length is
automatically generated for these labels.
Step 9 − Save your changes. The Create Object Directory Entry pop-up
appears and asks for a package. You may enter the package name in
which you are working. If you do not have any package then you may
create it in the Object Navigator or you can save your data element
using the Local Object button.
Step 10 − Activate your data element. Click the Activate icon
(matchstick icon) or press CTRL + F3 to activate the data element. A
pop-up window appears, listing the 2 currently inactive objects as
shown in the following screenshot.

Step 11 − At this point, the top entry labeled ‘DTEL’ with the name
Z_CUST is to be activated. As this is highlighted, click the green tick
button. This window disappears and the status bar will display the
message ‘Object activated’.
If error messages or warnings occurred when you activated the data
element, the activation log is displayed automatically. The activation log
displays information about activation flow. You can also call the
activation log with Utilities(M) → Activation log.
React.Component
React lets you define components as classes or functions. Components
defined as classes currently provide more features which are described
in detail on this page. To define a React component class, you need to
extend React.Component:

Class welcome extends React.Component{

render(){

return<h1>Hello, {this.props.name}</h1>

The only method you must define in a React.Component subclass is


called render().

The Component Lifecycle


Each component has several “lifecycle methods” that you can override to
run code at particular times in the process. You can use this lifecycle
diagram as a cheat sheet. In the list below, commonly used lifecycle
methods are marked as bold. The rest of them exist for relatively rare
use cases.
Mounting

These methods are called in the following order when an instance of a


component is being created and inserted into the DOM:
 constructor()
 static getDerivedStateFromProps()
 render()
 componentDidMount()
Updating

An update can be caused by changes to props or state. These methods


are called in the following order when a component is being re-rendered:
 static getDerivedStateFromProps()
 shouldComponentUpdate()
 render()
 getSnapshotBeforeUpdate()
 componentDidUpdate()
Unmounting

This method is called when a component is being removed from the


DOM:
 componentWillUnmount()
Error Handling

These methods are called when there is an error during rendering, in a


lifecycle method, or in the constructor of any child component.
 static getDerivedStateFromError()
 componentDidCatch()
Other APIs

Each component also provides some other APIs:


 setState()
 forceUpdate()
Class Properties
 defaultProps
 displayName
Instance Properties
 props
 State
DOM Rendering:

When the browser reads HTML code, whenever it encounters an HTML


element like html, body, div etc., it creates a JavaScript object called
a Node. Eventually, all HTML elements will be converted to JavaScript
objects.

Since every HTML element has different properties, the Node object will
be created from different classes (constructor functions). For example,
the Node object for the div element is created
from HTMLDivElement which inherits Node class. For our earlier HTML
document, we can visualize these nodes using a simple test as below.
The browser comes with built-in classes
like HTMLDivElement, HTMLScriptElement, Node etc.

After the browser has created Nodes from the HTML document, it has to
create a tree-like structure of these node objects. Since our HTML
elements in the HTML file are nested inside each other, the browser
needs to replicate that but using Node objects it has previously created.
This will help the browser efficiently render and manage the webpage
throughout its lifecycle.
(DOM Tree)

A DOM tree for our earlier HTML document looks like above. A DOM tree
starts from the topmost element which is html element and branches out
as per the occurrence and nesting of HTML elements in the document.
Whenever an HTML element is found, it creates a DOM node (Node)
object from its respective class (constructor function).

💡 A DOM node doesn’t always have to be an HTML element. When the
browser creates a DOM tree, it also saves things
like comments, attributes, text as separate nodes in the tree. But for the
simplicity, we will just consider DOM nodes for HTML elements
AKA DOM element. Here is the list of all DOM node types.
You can visualize the DOM tree in Google Chrome DevTools
Console as shown below. This will show you the hierarchy of DOM
elements (a high-level view of DOM tree) with properties of each DOM
element.

(Chrome DevTools Console)

JavaScript doesn’t understand what DOM is, it is not part of the


JavaScript specifications. DOM is a high-level Web API provided by the
browser to efficiently render a webpage and expose it publically for the
developer to dynamically manipulate DOM elements for various
purposes.
💡 Using DOM API, developers can add or remove HTML elements,
change its appearance or bind event listeners. Using DOM API, HTML
elements can be created or cloned in memory and maniuplated without
affecting the rendered DOM tree. This gives developers the ability to
construct highly dynamic web page with rich user experience.

CSS Object Model (CSSOM)


When we design a website, our intentions are to make it as good looking
as possible. And we do that by providing some styles to HTML elements.
In the HTML page, we provide styles to HTML elements
using CSS which stands for Cascading Style Sheets. Using
CSS selectors, we can target DOM elements and set a value to style
property such as color or font-size.

There are different methods of applying styles to HTML elements like


using an external CSS file, with embedded CSS using <style> tag, with
an inline method using the style attribute on HTML elements or using
JavaScript. But in the end, the browser has to do the heavy lifting of
applying CSS styles to the DOM elements.

Let’s say, for our earlier example, we are going to use the below CSS
styles (this is not the CSS used for the card shown in the screenshot).
For the sake of simplicity, we are not going to be bothered about how we
are importing the CSS styles in the HTML page.
(source: gist.github.com)

After constructing the DOM, the browser reads CSS from all the sources
(external, embedded, inline, user-agent, etc.) and construct a CSSOM.
CSSOM stands for CSS Object Model which is a Tree Like structure just
like DOM.

Each node in this tree contains CSS style information that will be applied
to DOM elements that it target (specified by the selector). CSSOM,
however, does not contain DOM elements which can’t be printed on the
screen like <meta>, <script>, <title> etc.

As we know, most of the browser comes with its own stylesheet which is
called as user agent stylesheet, the browser first computes final CSS
properties for DOM element by overriding user agent styles with CSS
provided by the developer properties (using specificity rules) and then
construct a node.

Even if a CSS property (such as display) for a particular HTML element


isn’t defined by either the developer or the browser, its value is set to
the default value of that property as specified by the W3C
CSS standard. While selecting the default value of a CSS property, some
rules of inheritance are used if a property qualifies for the inheritance as
mentioned in the W3C documentation.

For example, color and font-size among others inherits the value of the


parent if these properties are missing for an HTML element. So you can
imagine having these properties on an HTML element and all its children
inheriting it. This is called cascading of styles and that’s why CSS is an
acronym of Cascading Style Sheets. This is the very reason why the
browser constructs a CSSOM, a tree-like structure to compute
styles based on CSS cascading rules.
We can visualize the CSSOM tree for our earlier example using the
below diagram. For the sake of simplicity, we are going to ignore the
user-agent styles and focus on CSS styles mentioned earlier.

You might also like