25 - 26 - REST APIs
25 - 26 - REST APIs
Frontend Backend
(client-side) Internet (server-side)
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 3
Application Programming Interfaces
Application Programming Interfaces (APIs) are ways for computer
programs to communicate with each other
How can we handle communications over the internet?
• Manually define a protocol over TCP/UDP, open sockets, etc…
• Not very cost-effective, not very interoperable
• If we want to integrate n APIs, we’ll need to learn n different protocols
• CORBA, Java RMI, SOAP, …
• Dedicated protocols/architectures exist(ed), re-inventing an alternative to the
web
• Just use web protocols (HTTP)!
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 4
REST
• REST is not a standard or a protocol
• REST is an architectural style: a set of principles and guidelines that
define how web standards should be used in APIs
• Based on HTTP and URIs
• Provides a common and consistent interface based on «proper» use of
HTTP
• The prevalent web API architecture style with a 93.4% adoption rate1
[1] https://nordicapis.com/20-impressive-api-economy-statistics/
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 5
(A look back on) HTTP
• HyperText Transfer Protocol
• Two types of messages: Request and Response
Request Response
HTTP
Verb URI HTTP Version Status
Version
Request Header Response Header
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 9
Representational State Transfer (REST)
• Application State (on the Client)
• Resource State (on the Server)
• Trasferred using appropriate representations (e.g.: JSON, XML, …)
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 10
HTTP: Data Interexchange Formats
• Widely used formats include JSON and XML
{ <?xml version="1.0" encoding="UTF-8" ?>
"todos": [{ <root>
"todo": "Learn REST", <todos>
"done": false <todo>
}, { <text>Learn REST</text>
"todo": "Learn JavaScript", <done>false</done>
"done": true </todo>
}] <todo>
} <text>Learn JavaScript</text>
<done>true</done>
</todo>
</todos>
</root>
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 11
REST: Examples
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 12
REST: Nested Resources
• Sometimes, there is a hierarchy among resources
• A Company has 0..* Departments which have 0..* Employees…
• When designing an API, it is possible to define nested resources
• GET /listings/{id}/reviews lists all the reviews of a given listing.
• Keep in mind that every resource should have only one URI
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 13
REST: Filtering and Ordering
• Often, clients need to retrieve a list of resource with specific filtering
criteria or specific sorting in place (e.g.: sort listings by price)
• You may be tempted to add new paths as follows
HTTP verb/URI Meaning
GET /todos Retrieve a list of all saved To-do items
GET /todosSortedAsc Retrieve saved To-do items, sorted alphabetically
(ascending order)
GET /todos/filter/key Retrieve all To-do Items containing the «key» keyword
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 14
REST: Filtering and Ordering
HTTP verb/URI Meaning
GET /todos Retrieve a list of all saved To-do items
GET /todosSortedAsc Retrieve saved To-do items, sorted alphabetically
(ascending order)
GET /todos/filter/key Retrieve all To-do Items containing the «key» keyword
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 15
REST: Filtering and Ordering
• So, how do we handle these cases?
• You should not add new paths, but you should use query parameters
HTTP verb/URI Meaning
GET /todos Retrieve a list of all saved To-do items
GET /todos?sort=title&mode=asc Retrieve saved To-do items, sorted
alphabetically by title (ascending order)
GET /todos?q=key Retrieve all To-do Items containing the «key»
keyword
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 16
Securing a REST API
The JSON Web Token (JWT) Authentication/Authorization Scheme
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 17
API Authentication/Authorization
• REST APIs allow users to manipulate resources
• In most cases, we don’t want everyone to be able to do so
• Authentication: We want that only legit users can access the resources
• Authorization: We may also want that some users can access only
certain resources (e.g.: an employee shouldn’t be able to update its
own salary)
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 18
How to secure REST APIs
A widely-used authentication scheme is based on Tokens
Idea:
1. Clients send a request with username and password to the API
2. API validates username and password, and generates a token
3. The token (a string) is returned to the client
4. Client must pass the token back to the API at every subsequent
request that requires authentication (in the Authorization Header)
5. API verifies the token before responding
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 19
Token-based Authentication Scheme
Authentication Request
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 20
JSON Web Token (JWT)
• JWT is a widely-adopted open standard (RFC 7519)
• Allows to securely share claims between two parties
• A JWT token is a string consisting of three parts, separated by “.”
• Structure: Header.Payload.Signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX
VCJ9.eyJuYW1lIjoibHVpZ2kiLCJyb2x
lIjoiYWRtaW4iLCJleHAiOjE2NzAzOTg
0MzJ9.fopBYrax8wcB7rnPjCcOMc62IT
2lJdvyOdyixMWMZAQ
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 21
JWT: Header
• The JWT header contains information about the type of token and the
type of hashing function used to sign it, in JSON format
• It is encoded using Base64Url Encoding
• Note that this is merely an encoding, not an encryption! It can be easily be
inverted!
{
eyJhbGciOiJIUzI Base64Url Encoding "alg": "HS256",
1NiIsInR5cCI6Ik "typ": "JWT"
}
pXVCJ9
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 22
JWT: Payload
• The payload is a JSON object containing claims
• Some registered claims are recommended (e.g. «exp» indicates an
expiration date for the token)
• Claims are customizable (we can write any claim in the payload)
• It is encoded using Base64Url Encoding
{
eyJuYW1lIjoibHV "name": "luigi",
Base64Url Encoding
pZ2kiLCJyb2xlIj "role": "admin",
"exp": 1670398432
oiYWRtaW4iLCJle }
HAiOjE2NzAzOTg0
MzJ9
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 23
JWT: Signature
• To ensure that tokens are not tampered or forged, a signature is
included
• The signature is obtained by applying a cryptographic hashing
function to the string obtained by concatenating:
• The header of the token
• The payload of the token
• A secret key known only by the server that issues the token
• Actually, JWT signatures are a little bit more complex than that
• Check out HS256 or RS256 if you want to know more:
https://auth0.com/blog/rs256-vs-hs256-whats-the-difference/
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 24
Cryptographic Hashing Functions
Functions that map an arbitrary binary string (input) to a fixed-size binary
string (digest or hash)
Web Technologies Cryptographic 72bdf1226df1010dfb47cffaed85f5b35ae15ec9b482388691fa7a662a114113
Hashing Function
Web Technologies! (SHA2-256) 1a6791a2eab52c7c71d3e1225632d866b48a3abad91df15b2d44ab6004877993
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 25
JSON Web Token: Overview
{
eyJhbGciOiJIUzI Base64Url Encoding "alg": "HS256",
1NiIsInR5cCI6Ik "typ": "JWT"
}
pXVCJ9.eyJuYW1l
IjoibHVpZ2kiLCJ {
Base64Url Encoding "name": "luigi",
yb2xlIjoiYWRtaW "role": "admin",
"exp": 1670398432
4iLCJleHAiOjE2N }
zAzOTg0MzJ9.fop
HMACSHA256(
BYrax8wcB7rnPjC base64UrlEncode(header) + "." +
cOMc62IT2lJdvyO base64UrlEncode(payload),
secret_key
dyixMWMZAQ )
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 26
Implementing a REST API
Practical demonstration with JAX-RS
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 27
Implementing a REST API
• REST APIs are conceptually simple
• We just need to listen for HTTP requests, and handle them
• Typically, in prevalently synchronous languages such as Java, a new thread is
created to handle the request
• Once done handling the request, we send a HTTP response accordingly
• You should already know how to implement a REST API using low-level
languages and sockets from the Computer Networks/Operating
Systems Lab courses.
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 28
Implementing a REST API from scratch
Implementing a REST API from scratch is feasible and within our reach
There’s quite a lot of efforts involved though…
• We need to parse the HTTP requests
• Possibly, we need to deserialize objects received as JSON/XML in requests
• We need to prepare HTTP responses
• We need to serialize objects to encode them as JSON/XML in responses
• We need to manage request routing
• We need to manage request filtering and authorization
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 29
(Web) Frameworks
Web Frameworks can help us implement REST APIs without dealing with
these repetitive, «common» core tasks
What’s a Framework?
• A collection of reusable components, tools, libraries, and practices
designed to simplify software development and maintenance
• Frameworks do not directly implement any user feature, but can be
used to simplify the development of the actual features
• Their purpose is to provide a foundation for software development by
offering ready-made solutions for common problems, enforcing best
practices, and ensuring consistency across applications.
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 30
Software Library Framework
• Essentially a set of functions we • Embody some abstract design,
can call to get some job done with more behaviour built-in
• Each call does some work and • User-written code can be
then returns control to the caller plugged-in into the framework
• User code (e.g.: our main • The framework is in control of the
method) is in control of the execution flow and calls user
execution flow code when appropriate
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 31
Inversion of Control (IoC) Principle
• IoC is a defining feature of frameworks
• The control flow is inversed from traditional imperative programming
• The responsibility of managing the control flow is shifted from the developer to
a framework
• A.k.a. Hollywood’s Law: “Don't call us, we'll call you”.
Request Response
Library A Library B Framework
1 6
2 3 4 5 2 3 4 5
Request Response
User Code User Code User Code
1 6
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 32
Opinionated Frameworks
• Frameworks can be more or less opinionated
• A (strongly) opinionated framework comes with
a rigid set of pre-defined conventions, best
practices, and decisions made by the
framework's creators. It enforces a specific way
of doing things, and leaves less wiggle room to
devs.
• Unopinionated frameworks do not enforce a
specific way of doing things Keep in mind, this framework
has really strong opinions…
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 33
Opinionated Frameworks
Pros Cons
• Ensure higher levels of • May have a steeper learning
consistency across different curve
projects • May not be flexible enough for a
• Can speed up development, certain project
reducing decision fatigue
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 34
Web Frameworks (Server-side)
• Many web frameworks to choose from (e.g.: see Wikipedia)
Starly
One of the above is not a real framework, but a Pokemon. Can you tell which one?
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 35
Practical Demonstration
Implementing a REST API with Jakarta EE (JAX-RS)
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 36
JAKARTA ENTERPRISE EDITION (EE)
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 38
A REST API USING JAX-RS
• Let’s take a look at the code
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 39
MAVEN ARCHETYPE
• The easiest way to get started is
to use a Maven Archetype
• Archetypes are basically
templates, including
dependecies and boilerplate
code
• We’ll use the jersey-quickstart-
grizzly2 archetype from Maven
Central
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 40
ADD SUPPORT FOR JSON
• After creating your project from the archetype, remember to include
JSON support by uncommenting the following dependency in the
pom.xml
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 41
CODE EXAMPLES
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 42
CODE EXAMPLES
@Path("/todos")
public class TodoController {
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<TodoItem> getAll() {
return TodoItemDAO.getAll();
}
}
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 43
CODE EXAMPLES
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addTodoItem(TodoItem todo){
try {
TodoItemDAO.add(todo);
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(e.getMessage()).build();
}
}
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 45
OPENAPI: DESCRIBING A REST API
• OpenAPI (formerly Swagger) is an open,
formal standard to describe HTTP APIs
• Why?
• Standardization: ensures consistent
documentation practices
• Documentation: can be used to automatically
generate comprehensive docs
• Code generation: Allows for automatic
generation of client libraries and server stubs
• Machine and human-readable: enables
automated discovery and more
• Most broadly adopted industry standard
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 46
THE OPENAPI SPECIFICATION
• OpenAPI Descriptions are written as structured text documents
• Each document represents a JSON object, in JSON or YAML format
• These specification files describe version of the OpenAPI specification
(openapi), the API (info) and the endpoints (paths)
# YAML format // JSON format
openapi: 3.1.0 {
info: "openapi": "3.1.0",
title: A minimal specification "info": {
version: 0.0.1 "title": "A minimal specification",
paths: {} # No endpoints defined "version": "0.0.1"
},
"paths": {} // No endpoints defined
}
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 47
THE OPENAPI SPECIFICATION: PATHS
• The API Endpoints are called Paths in the OpenAPI specification
• Path objects allow to specify a sequence of endpoints
• For each endpoint, its supported methods
• For each method,
• Expected input parameters (if any) (e.g.: path parameters, headers, etc…)
• Request body (if any)
• Possible responses
• And more!
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 48
THE OPENAPI SPECIFICATION: PATHS
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 49
/auth:
post:
PATH EXAMPLE description: Authenticate user
produces:
- application/json
requestBody:
• /auth endpoint, POST method description: user to authenticate
required: true
• Expects Request Body content:
containing a JSON object with application/json:
type {usr: string, pwd: string} schema:
type: object
• Returns 200 OK on success, 401 properties:
usr:
Unauthorized when credentials type: string
are invalid example: Kyle
pwd:
type: string
example: p4ssw0rd
responses:
200:
description: User authenticated
401:
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm Invalid credentials50
description:
WORKING WITH OPENAPI SPECIFICATIONS
• Writing an OpenAPI specification for an API is quite a lot of work
• What can we do with an OpenAPI specification?
openapi: 3.1.0
info: Design Support
title: My API Detect errors and inconsistencies
version: 1.0.0
paths:
/auth:
Generate Code
post:
Server stubs, client SDKs, tests
# ...
/todos:
get:
# ... Document
post: Generate interactive docs
# ...
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 51
OPENAPI: OPEN SOURCE TOOLS
• OpenAPI is supported by a number of mature, open-source tools
• Some widely used open-source tools are reported as follows:
• Swagger Editor: https://swagger.io/tools/swagger-editor/
• Swagger Codegen: https://swagger.io/tools/swagger-codegen/
• Swagger UI: https://swagger.io/tools/swagger-ui/
• You can also check them out in a web browser, without downloading
anything: https://editor.swagger.io/
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 52
OPENAPI: SWAGGER EDITOR
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 54
OPENAPI-DRIVEN DEVELOPMENT
• Often, developers start working on an API by defining its specification
before writing any actual code
• This approach is also referred to as OpenAPI-driven development
• This way, they can exploit code generation capabilities to the fullest
• The approach also promotes independence between the different
teams involved in a project (front-end, back-end, QA). The API
definition keeps all these stakeholders aligned
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 55
REFERENCES (1/2)
• The Little Book on REST Services
By Kenneth Lange
Freely available at https://www.kennethlange.com/books/The-Little-Book-on-REST-Services.pdf
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 60
REFERENCES (2/2)
• OpenAPI
Official Website
https://www.openapis.org/
https://learn.openapis.org/ (Recommended reads from this link: Getting started, Introduction)
https://spec.openapis.org/oas/v3.1.0 (Full specification for OpenAPI 3.1.0)
For the Web Technologies course, you need to know what the OpenAPI specification standard is, why it has
been introduced, and what it can be used for. You are not required to learn how to write OpenAPI specification
files from scratch.
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 61
EXAMPLES WITH DIFFERENT FRAMEWORKS
• To-do List REST API using JakartaEE (Java)
By Luigi Libero Lucio Starace
Includes source code, Dockerfile and instructions.
https://github.com/luistar/jakartaee-rest-example
Luigi Libero Lucio Starace, Ph.D. - University of Naples Federico II - Software Engineering Course - Lecture 25 - The REST Paradigm 62