Week-8 Full Stack
Week-8 Full Stack
What is an API?
Application Programming Interface (API) is a software interface that allows two
applications to interact with each other without any user intervention. API is a collection of
software functions and procedures. In simple terms, API means a software code that can be
accessed or executed.
API is defined as a code that helps two different software’s to communicate and exchange data
with each other.
API Example:-
Let see how API works using simple daily life example. Imagine that you went to a restaurant
to take lunch or dinner. The waiter comes to you gives you a menu card, and you will provide
personalize it order like you want a veg sandwich but without onion.
After some time, you will get your order from the waiter. However, it is not that simple as it
looks as there is some process that happens in between.
Here, the waiter plays an important part as you will neither go to the kitchen to collect your
order nor will you tell the kitchen staff what you want all this done by the waiter.
API also does the same by taking your request, and just like the waiter tell the system what you
want and give a response back to you.
An application programming interface is a set of rules that define how computers, applications,
or machines can talk to each other. You can think of it this way: the typical user interface is
intended for use by a human being, while APIs are intended for use by an application or
computer.
Most web APIs sit between the application and the web server. The user initiates an API call
that tells the application to do something, then the application will use an API to ask the web
server to do something. The API is the middleman between the application and the web server,
and the API call is the request. And every time you use software to communicate with other
software or online web servers, you’re using APIs to request the information you need. It’s
important to note that while web APIs are the most common, APIs aren’t limited to the web.
There are APIs for virtually every machine or system that expects to interact with other
machines or systems.
Example :-Imagine you’re a customer at a restaurant. The waiter (the API) functions as an
intermediary between customers like you (the user) and the kitchen (web server). You tell the
waiter your order (API call), and the waiter requests it from the kitchen. Finally, the waiter will
provide you with what you ordered.
The waiter is the intermediary between you and the kitchen. In this example, as a customer,
you don’t need to know how the kitchen or the restaurant operates in order to get what you
want the food. You just need to know how to order it.
APIs make it easier to reuse functionality and simplify coding for developers, but they also
provide secure connections between systems, which can improve the user experience. The API
acts as an intermediary between systems by translating data formats into something the other
program understands. This reduces any incompatibility between systems and removes the need
for costly software conversions.
here are three reasons why you need an APIs
API types
APIs come in four different modalities. Each of these covers a different access level or, in the
case of web APIs, a different usage.
1. Open APIs
2. Partner APIs
3. Internal APIs
4. Composite APIs
1.Open APIs: - Open APIs, or public APIs, come with limited or no access restrictions. This
essentially allows any developer to make requests to these APIs. These APIs may have some
limits. A developer may have to register an account to receive an API key, for instance.
Additionally, limits may be placed on things like the number of requests in a given time frame.
open APIs are distinguished by being intended for widespread external use. They are meant
for third-party developers to be able to access and make use of the API as they need.
2.Partner APIs: - Partner APIs require authorization of some kind to use. They still allow
external access, but are not intended for the general public to have access to. Instead, partner
APIs are designed for use by pre-approved individuals, teams, or organizations.
A partner API may allow public access through a paid subscription or it may limit access to
developers with a business relationship. Typically, the developer has an API key, as with open
APIs, that require registration. But with partner APIs, keys tend to be given out more sparingly
and with more access restrictions.
3.Internal APIs: - Internal APIs, also called private APIs, disallow external access. Instead,
these APIs can only be accessed by developers within a company or even within the particular
application to which the API belongs.
These APIs are the most limited. APIs are incredibly useful in defining communication
between applications and services, and this even applies when communication is within a single
organization.
4.Composite APIs: - Composite APIs allow for requests to be bundled or chained together,
which, in turn, allows developers to receive single responses for request collections.
These APIs are useful for reducing server load and network traffic when you expect frequent
requests to multiple API endpoints. Calls get made less frequently, resulting in reductions to
server processing time and the number of requests across the network.
- Types of API Protocols (SOAP, REST) Common API examples
Every API uses a particular protocol. An API’s protocol defines the rules for how it can
communicate. These rules make explicit the kinds of requests that can be made, what the API’s
responses look like, and what kinds of data the API can send and receive.
SOAP stands for Simple Object Access Protocol is a network platform used in a web
service to exchange or communicate data between two different machines on a network. It uses
the XML format of data to transfer messages over the HTTP protocol. In Web services, SOAP
allows the user request to interact with other programming languages. In this way, it provides
a way to communicate between applications running on different platforms (Operating system),
with programming languages and technologies used in web service.
SOAP Message:-The SOAP message contains the following information in the XML format,
as given below.
It contains information about the message structure and instructions during processing
on the network.
The SOAP contains an envelope that represents the starting and end of the message in
the XML format.
In the message, the header is an optional element that contains application-specific
information such as authentication, authorization, and payment etc.
A fault element is an optional element that shows an error message during the
processing of the information.
Characteristics of SOAP
It is an open standard protocol used in the web service to communicate via internet.
It is used to broadcast a message over the network.
It is used to call remote procedures and exchange documents.
It can be used on any platform and can support multi-languages. So, it is a platform and
language independent.
It uses the XML format to send messages over the HTTP protocol.
The structure of a SOAP message consists of an envelope, header, and body element
The SOAP building block describes what XML data is sent to the web service and client
application. The following diagram represents the SOAP building block.
SOAP Envelope: Envelope is used to define the start and end of the SOAP message. It contains
the details of the SOAP message. It is an important element of the XML documents
SOAP Header: It is an optional element in which the header contains the credentials
information such as authorization, authentication, etc. is used during the processing of a SOAP
message.
SOAP Body: It is an important element of the SOAP message that contains request and response
information in the XML format. It defines the actual content of the message to be sent between
the client and the webserver.
SOAP Fault: The SOAP Fault element is an optional element used to display an error message
encountered during the transmission of a SOAP message. It holds the status of SOAP messages
and errors.
Advantages of SOAP
o It is a lightweight communication protocol used for exchanging data between two
machines over the network.
o It is a platform-independent operating system that can run on Linux, Windows and
macOS.
o SOAP uses a default protocol to send the message over a network, and all web
applications also support it.
o It has an XML format that includes an envelope, header, body, and fault element as a
SOAP message during the message's processing
Disadvantages of SOAP
o SOAP is used only XML format data in web service, whereas JSON and other
lightweight formats are not supported by it.
o It is slow because it uses XML format, whereas the payload for a simple string message
is large.
o There are no security features in the SOAP specification.
o There is no state reference for the remote object in the SOAP client.
REST: - REST stands for Representational State Transfer. It is an architectural style that
provides standards between computer systems on a web service. It is a set of constraints used
to create a lightweight, scalable, and maintainable web service that facilitates easy
communication. It is a set of constraints used to create a lightweight, scalable and maintainable
web service that makes easy communication with each other.
All web services are based on the REST; hence it is called a RESTful service. The purpose of
developing a RESTful web service is to make the web service more effective.
REST Characteristics
o It is a Stateless server.
o It supports JSON and XML
o It is simple than SOAP.
o It has well-maintained documentation that reflect each change in the architectures of
the REST.
o It is a simple approach to build the client and server service.
o It follows standard protocol such as HTTP, HTTPS and FTP.
o It provides a way to connect with server-side applications.
o It is based on architectural style for designing simple, lightweight, and distributed web
services compared to SOAP.
2. Weather snippets
When you do a quick search for information on the local weather, it’s understandable for you
to think that Google has sourced and provided this info on its own. Yet this isn’t the case.
Google uses other software to gain this weather information, and an API is used as the bridge
to get this information to the user after their search query.
4. Travel booking
Everyone has used a travel website like Expedia or Trivago at some point. As a result, everyone
has experienced one of the most beneficial API uses around. These sites pull information such
as prices, flight times, hotel availability, etc., from various sources. They then package all of
this info and present it to users, ensuring they don’t have to look elsewhere for certain details
about their prospective trip.
API endpoints
A social media site’s API allows users to retrieve user profiles, images, and content. A new
site’s API gives users access to its news articles, videos, podcasts, and authors. But users need
to use the correct endpoint to specify the resource they want to access. In these sites, the URL
functions as the endpoint.
Organizations use APIs to move critical information, transactions, and processes, among
others. Endpoints API are important because they help point the specific location of the
resources that need to be accessed. They also make sure the software works with the API as
designed. Website and software APIs must connect with endpoints API correctly to perform
well.
- HTTP working
Hypertext Transfer Protocol provides a network protocol standard that web browsers and
servers use to communicate.
The following diagram shows a very architecture of a web application and depicts where HTTP
sits
The HTTP protocol is a request/response protocol based on the client/server based architecture
where web browsers, robots and search engines, etc. act like HTTP clients, and the Web server
acts as a server.
Client
The HTTP client sends a request to the server in the form of a request method, URI, and
protocol version, followed by a MIME-like message containing request modifiers, client
information, and possible body content over a TCP/IP connection.
Server
The HTTP server responds with a status line, including the message's protocol version and a
success or error code, followed by a MIME-like message containing server information, entity
meta information, and possible entity-body content.
1.Get Method
Get method is used to retrieve or get the information from the given server using a given URL.
2.Post Method
Post is used for sending data to the server such as uploading a file or transferring some data or
adding a new row to the back end table to any kind of web form.
3.PUT Method
The PUT method is most often used to update an existing resource.
In HTTP.PUT method, the resource is first identified by the URL and if it exists, then it is
updated, otherwise, a new resource is created.
4.DELETE METHOD
The DELETE method is used to delete a resource specified by its URI
Understanding of JSON structure for API request and response
data
JSON stands for JavaScript Object Notation.it is a lightweight format for storing and
transporting data and it is used when data is sent from a server to a web page. JSON is "self-
describing" and easy to understand.
The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is
text only. Code for reading and generating JSON data can be written in any programming
language
.JSON Example: -
{
"employees":[
{"firstName":"John", "lastName":"Doe" },
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones" }
]
}
Basics of REST
REST is an API architecture style. It stands for representational state transfer. REST
specifies how data is presented to a client in a format that is convenient for the client. Data
exchanges happen either in JSON or XML format.
RESTful APIs function just about the same way standard TCP/IP requests function, except
there are no clients and servers here, but just two applications talking to each other.
Overview of REST
The abstract idea behind Application Programming Interface (API) which helps to
communicate with other systems or applications came in to existence since early days of
programming.
The concept of setting up rules to make the inter communication between software systems
feasible and effective lead to old intercommunication protocols like RPC, CORBA.
As the software domain grew into a bigger dimension with innumerable challenges and
demands, several new communication protocols evolved. This gradual evolution in inter
communication between software systems lead to the wide spread use of APIs.
Evolution of API
API evolution is the concept of striving to maintain the "I" in API, the request/response
body, query parameters, general functionality, etc., only breaking them when you
absolutely have to. It's the idea that API developers bending over backwards to maintain a
contract, no matter how annoying that might be, is often more financially and logistically
viable than dumping the workload onto a wide array of clients.
At some point change cannot be prevented, so at that time evolution suggests you provide
sensible warnings to clients, letting them know if a feature they're using is going away, and
not bothering them otherwise
API use has increased over the past years, that several most popular web applications today
would not be possible without APIs.
1.Remote procedure Call(RPC)-1981
2. Common Object Request Broker Architecture (CORBA)-1991
3. Simple Object Access Protocol (SOAP)-1998
4. REpresentational State Transfer (REST)-2000
5.GraphQL-2012
REST components
A REST message contains these components:
Resource Path
HTTP Verb
Body
Header
Resource Path (request target)
The path to the resource (object) to be acted upon. The ID of the resource must be provided
in the path.
For example, the following resource path identifies a specific transaction (resource) in our
database:
https://apitest.cybersource.com/pts/v2/payments/
The main part of the resource path begins after the host, apitest.cybersource.com.
/pts/v2/payments
is the address (resource) on the CyberSource end that processes transaction detail requests.
CyberSource returns a request ID that provides transaction details you can use for follow -
up transactions, queries, or reference.
HTTP Verb
The verb defines the action to take regarding the resource:
Available verbs:
POST—Creates a resource
GET—Retrieves one or more resources
PUT—Updates a resource
DELETE—Deletes a resource
These verbs are referred to as CRUD operations. They allow
the Creation, Retrieval, Update and Deletion of resources.
Body
A POST or PUT request has a body. A GET request has no body. REST uses JSON
(JavaScript Object Notation) as its content format. To help with the structure of your
requests, you can generate sample CyberSource JSON request messages using the API
Reference docs in the CyberSource Developer Center .
Header
The header is a collection of fields and their associated values that provides information
about the message to the receiver. Think of it as metadata about the message. The header
also contains authentication information that tells CyberSource that the message is
legitimate.
Process View: - Process view illustrates the interaction relationship among components.
The interaction is in the form of data flow in a system.
Connector View: - connector view of architecture tells on the mechanics of the
communication between components. The REST-based architecture looks in the constraints
that define the generic resource interface.
client connectors examine the resource identifier in order to select appropriate
communication mechanisms for each request. REST does not restrict communication to a
particular protocol, but it does constrain the interface between components.
Data View: - A data view of architecture tells the application state as information flows
through the components.
REST constraints
For an API to be RESTful there are six rules that it needs to follow.
The rules are as follows:
1. Uniform interface
2. Client–server
3. Stateless
4. Cacheable
5. Layered system
6. Code on demand
1.Uniform Interface
The API should facilitate communication between the client and server as they exchange
data. To efficiently exchange data, we need a uniform interface.
If your system is using well known protocols and techniques, it’s easily implemented. Data
should be exchanged using standard formats JSON or XML .
2.Client-server architecture
The main purchase of an API is to connect two pieces of software – software might be
custom built and run, off the shelf, or a Software as a Service. The client makes requests
and the server gives responses – it’s important that they stay separate and independent.
well designed relationship shouldn’t need to be updated every time applications on each
end change.
3.Stateless
It’s important that each endpoint in the API be stateless which means each call mus t be
handled independently and have no knowledge of what happened from other calls.
A stateless API means that the server receives everything from a client that they need to
identify them and what they want in each request.
The major advantages of a stateless API are:
that they can handle more clients because less resources are used, and each request is
independent of previous ones.
4.Cacheable
APIs can have a lot of overhead when they process requests – making repeated requests for
data that rarely changes or for the exact same data doesn’t normally make sense.
A cache allows us to temporarily store data locally for a agreed upon period of time. So
essentially, if the client goes to make the call again and the agreed upon time hasn’t been
fully spent it will use the stored version.
5.Layered System
REST allows us to build a layered system architecture meaning that multiple servers may
potentially respond to a request. A client shouldn’t be able to easily tell what system is
responding to their request especially if it’s behind an API Gateway.
6.Code on Demand
Code-on-Demand (COD) is the only optional constraint in REST. It allows clients to improve
its flexibility because, in fact, it is the server who decides how certain things will be done. For
example, client can download a javascript, java applet or even a flash application in order to
encrypt communication so servers are not aware of any encryption routines / keys used in this
process.
REST Properties
It is stateless
It supports JSON and XML
It is simple than SOAP
Documentation
Error messages
Here is the complete diagram to easily understand REST API’s principles, methods,
The Six Principles
3. Cacheable: To improve network efficiency, we add cache constraints to form the client-
cache-stateless-server style. Cache constraints require that the data respond to a request
with the implicit or explicit label as cacheable or non-cacheable. If a response is cacheable,
then a client cache is given the right to reuse that response data for later, equivalent requests.
4. Layered System: A client cannot ordinarily tell whether it is connected directly to the
end server or an intermediary along the way. Intermediary servers may improve system
scalability by enabling load-balancing and by providing shared caches. Layers may also
enforce security policies.
In short, Spring Boot is the combination of Spring Framework and Embedded Servers. In
Spring Boot, there is no requirement for XML configuration.
Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-
grade Spring Based Applications with minimum efforts.
Spring Boot follows a layered architecture in which each layer communicates with the layer
directly below or above (hierarchical structure) it.
Before understanding the Spring Boot Architecture, we must know the different layers present
in it. There are four layers in Spring Boot are as follows:
o Presentation Layer
o Business Layer
o Persistence Layer
o Database Layer
Presentation Layer: The presentation layer handles the HTTP requests, translates the JSON
parameter to object, and authenticates the request and transfer it to the business layer. In
short, it consists of views i.e., frontend part.
Business Layer: The business layer handles all the business logic. It consists of service
classes and uses services provided by data access layers. It also
performs authorization and validation.
Persistence Layer: The persistence layer contains all the storage logic and translates
business objects from and to database rows.
Database Layer: In the database layer, CRUD (create, retrieve, update, delete)
operations are performed.
o The client makes the HTTP requests (PUT or GET).
o The request goes to the controller, and the controller maps that request and
handles it. After that, it calls the service logic if required.
o In the service layer, all the business logic performs. It performs the logic on the
data that is mapped to JPA with model classes.
o A JSP page is returned to the user if no error occurred.
RestController: RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class to
handle the requests made by the client.
The RestController allows to handle all REST APIs such as GET,PUT,POST,DELETE
Spring Initializr is a web-based tool using which we can easily generate the structure
of the Spring Boot project. It also provides various different features for the projects
expressed in a metadata model. This model allows us to configure the list of dependencies
that are supported by JVM.
Controller classes as the presentation layer. Keep this layer as thin as possible and
limited to the mechanics of the MVC operations, e.g., receiving and validating the
inputs, manipulating the model object, returning the
appropriate ModelAndView object, and so on. All the business-related operations
should be done in the service classes. Controller classes are usually put in
a controller package.
Service classes as the business logic layer. Calculations, data transformations, data
processes, and cross-record validations (business rules) are usually done at this layer.
They get called by the controller classes and might call repositories or other services.
Service classes are usually put in a service package.
Repository classes as data access layer. This layer’s responsibility is limited to Create,
Retrieve, Update, and Delete (CRUD) operations on a data source, which is usually a
relational or non-relational database. Repository classes are usually put in a repository
package.
Consider below Spring MVC web application using Spring boot and thymeleaf. We have
created a three-layer architecture and each layer is mapped to the corresponding package.
For example:
ORM is a programming ability to covert data from object type to relational type and vice versa.
The main feature of ORM is mapping or binding an object to its data in the database. While
mapping we have to consider the data, type of data and its relations with its self-entity or entity in
any other table.
Advanced Features
Idiomatic persistence: It enables you to write the persistence classes using object oriented
classes.
High Performance: It has many fetching techniques and hopeful locking techniques.
Reliable: It is highly stable and eminent. Used by many industrial programmers.
ORM Architecture
The below architecture explains how object data is stored into relational database in three phases.
Phase1
The first phase, named as the Object data phase contains POJO(Plain Old Java Object) classes,
service interfaces and classes. It is the main business component layer, which has business logic
operations and attributes.
For example let us take an employee database as schema-
Employee POJO class contain attributes such as ID, name, salary, and designation. And
methods like setter and getter methods of those attributes.
Employee DAO(Data Access Object)/Service classes contains service methods such as
create employee, find employee, and delete employee.
Phase 2
The second phase named as mapping or persistence phase which contains JPA provider, mapping
file (ORM.xml), JPA(Java Persistence API) Loader, and Object Grid.
JPA Provider: The vendor product which contains JPA flavor (javax.persistence). For
example, Eclipselink, Toplink, Hibernate, etc.
Mapping file: The mapping file (ORM.xml) contains mapping configuration between the
data in a POJO class and data in a relational database.
JPA Loader: The JPA loader works like cache memory, which can load the relational grid
data. It works like a copy of database to interact with service classes for POJO data
(Attributes of POJO class).
Object Grid: The Object grid is a temporary location which can store the copy of relational
data, i.e. like a cache memory. All queries against the database is first effected on the data
in the object grid. Only after it is committed, it effects the main database.
Phase 3
The third phase is the Relational data phase. It contains the relational data which is logically
connected to the business component. only when the business component commits the data, it is
stored into the database physically. Until then the modified data is stored in a cache memory as a
grid format. Same is the process for obtaining data.The mechanism of the programmatic interaction
of above three phases is called as object relational mapping.
Advantages of ORM Tool
It saves time and efforts.
It gives pace to development process.
It reduces the development cost.
It provides connectivity to the database.
It makes development more object-oriented.
Easy transaction management.
No need to implement database manually.
Speeds-up Development - eliminates the need for repetitive SQL code.
JPA is a specification and several implementations are available. Popular implementations are
Hibernate, EclipseLink and Apache OpenJPA.
JPA permits the developer to work directly with objects rather than with SQL statements.
The mapping between Java objects and database tables is defined via persistence metadata. The
JPA provider will use the persistence metadata information to perform the correct database
operations.
JPA metadata is typically defined via annotations in the Java class. Alternatively, the metadata can
be defined via XML or a combination of both. A XML configuration overwrites the annotations.
Most JPA persistence providers offer the option to create the database schema automatically based
on the metadata.
Entity: -
A class which should be persisted in a database it must be annotated with javax.persistence.Entity.
Such a class is called Entity.
JPA uses a database table for every entity. Persisted instances of the class will be represented as
one row in the table. All entity classes must define a primary key, must have a non-arg constructor
and or not allowed to be final. Keys can be a single field or a combination of fields.
JPA allows to auto-generate the primary key in the database via
the @GeneratedValue annotation. By default, the table name corresponds to the class name. You
can change this with the addition to the annotation @Table(name="NEWTABLENAME").
Persistence of fields:-
The fields of the Entity will be saved in the database. JPA can use either your instance variables
(fields) or the corresponding getters and setters to access the fields.
By default, each field is mapped to a column with the name of the field. You can change the default
name via @Column (name="newColumnName").
@GeneratedValue Together with an ID this annotation defines that this value is generated automatically.
Relationship Mapping:-
JPA allows to define relationships between classes, e.g. it can be defined that a class is part of
another class (containment). Classes can have one to one, one to many, many to one, and many to
many relationships with other classes.
Relationship annotations:
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
Entity Manager:-
The entity manager javax.persistence.EntityManager provides the operations from and
to the database, e.g. find objects, persists them, remove objects from the database, etc.
Persistence units:-
The EntityManager is created by the EntityManagerFactory which is configured by the persistence
unit. The persistence unit is described via the persistence.xml file in the META-INF directory of
the source folder. A set of entities which are logical connected will be grouped via a persistence
unit. The persistence.xml file defines the connection data to the database, e.g. the driver, the user
and the password.
@Configuration
@EnableJpaRepositories(basePackages = {
"net.petrikainulainen.springdata.jpa.todo"
})
@EnableTransactionManagement
class PersistenceContext {