REST APIs
Fekher Nouioui
>Plan
Our Agenda
1. Introduction to APIs
2. Transport Layer: HTTP
3. Data Exchange Formats
4. REST
5. REST Specification: Open API
Introduction to APIs
Why we need an API
2 systems A and B want to communicate with each other.
System A System B
Operating System Windows Linux
Programming Java Python
Language
The systems are very different, and they need a common ground to communicate with each
other.
We want to achieve Interoperability
We do this through APIs
What is an API
API stands for Application Programming Interface.
APIs are used for Applications to communicate with each others Programmatically using an
Interface.
API is “a set of functions and procedures” that allow you to access and build upon the data and
functionality of an existing application.
Advantages of using API
Advantages of using an API:
• Language/OS agnostic: any client (different language or platform) can consume the API with a
standard Interface (contract).
• Faster integration and reuse: you can connect systems and reuse existing services instead of
building from scratch.
• Cost efficiency: reduced development time and maintenance for integrations; reuse lowers
total cost.
An API call happens in 3 steps:
1. Application A makes a request to application B
2. a program is run in application B to process the request
3. The program sends back the response from application B to application A
Naming:
• Application A is called Client.
• Application B is called Server.
Transport Layer: HTTP
Web API
Web API is an API that is exposed through the Web.
Web APIs rely on Web protocols to do their job.
=> We use HTTP for this
HTTP and its content
HTTP (HyperText Transfer Protocol) is an application layer protocol. It’s the fundamental protocol
for transferring data over the internet.
Content of HTTP Request/Response:
• Start Line (The only mandatory part)
• Headers
• Blank Line
• Body
Start Line
Content Request Response
HTTP Version HTTP/1.1 HTTP/1.1
Method Example: GET, POST, PUT, DELETE, …
Endpoint Example: /users
Parameter Example: ?age=30
Status Code Example: 200 OK
Format {method} /{endpoint}?{parameter} {HTTP {HTTP Version} {Status Code}
Version}
Example GET /users?age=30 HTTP/1.1 HTTP/1.1 200 OK
Headers
What they are:
• Metadata lines that accompany the start line in HTTP requests or responses.
• Each header is a name-value pair: Header-Name: value
• Headers are case-insensitive; the conventional form uses Title-Case for readability.
Request Headers example:
• Host:
• What it does: Specifies the target host
name (used by the server to route the
Response headers
request).
• Content-Type:
• Host: [Link]
• What it does: Indicates the media type
• Authorization:
of the response body.
• What it does: Carries credentials for
• Content-Type: application/json;
authentication/authorization.
charset=utf-8
• Authorization: Bearer
your_jwt_token_here
• Accept:
• What it does: Indicates the media types
the client can handle in the response.
• Accept: application/json
Body
The data that we send (in post/put/delete ….) to the application B (Server).
The content-Type header describes the type of content in the HTTP Body:
HTML,XML,JSON,image,video, audio, …
HTTP Methods
HTTP methods: In total we have 9 HTTP methods.
We will focus on 5:
Method Description Idempotent
GET Retrieve a resource (Read)
POST Create a new resource (Create)
PUT Create or completely replace a resource at a known
(Update)
PATCH Apply partial updates to a resource (Update)
DELETE Remove a resource (Delete)
Idempotence: An operation is idempotent if performing it once or multiple times with the same
input yields the same final state and the same result as a single execution. Repeating the
operation should not cause additional changes after the first one.
More Details: [Link]
HTTP Status
HTTP Status varies from 100 to 599.
Min Max What id does
100 199 Informational Responses
200 299 Successful Responses
300 399 Redirection Messages
400 499 Client Error responses
500 599 Server Error responses
More Details: [Link]
API Clients
To interact with the API and test it, we need a client that is able to make API calls over HTTP, a lot of
tools exist:
Postman
SoapUI
cURL (Client URL)
Data Exchange
Formats
Data Exchange Format
For the APIs to be interoperable, they need to use a common language to communicate with
each other.
The widely used Data exchange Format are:
• JSON: The most famous.
• XML: Used more in older APIs.
• YAML: Popular for configurations.
XML
XML (eXtensible Markup Language)
File extension: .xml
Provides also a schema file to define the structure and validate the xml file (.xsd extension).
Less and less used nowdays as it’s:
• Verbose: Very large payloads wchich results in increased bandwidth and parsing time
(Consume more resources).
• Readability: Not human readable.
JSON
JSON (JavaScript Object Notation)
File extension: .json
It is based on key value pairs: the literal object syntax of JavaScript but the key is in “”.
Established as the standard now days:
• Less Verbose: Smaller payloads which results in less resource consumption.
• Readability: Easily Readable by humans.
REST
REST
REST (REpresentational State Transfer) is an architectural style (a set of rules) to build Web APIs
based on HTTP.
It’s less strict than SOAP and it’s not considered as a Protocol.
• You design a web API that is consumed through HTTP.
• This API follows certain constraints.
=> Your API is considered a REST API.
These Acceptance criteria:
• Client-Server
• Stateless
• Cacheable
• Uniform Interface
• Layered System
• Code on Demand (optional)
Client Server
Client-Server
Separation of concerns:
• Clients handle UI.
• Servers handle data and logic.
=> This is established considering that the internet is built around the client server paradigm.
Stateless
• A stateless server does not keep any memory of previous requests about a client.
• Each request must include everything the server needs to process it (identification,
permissions, inputs).
Why stateless is useful
• Easy to scale: any server instance can handle a request without loading a per-client session.
• Simple load balancing: requests can be routed to any server since no session state is tied to a
specific one.
Cacheable
Responses can be cached.
If the response is cached, any intermediate can cache it:
• Browser caches (client-side): store responses to GET/HEAD requests for reuse.
• Intermediate caches (CDNs, reverse proxies, forward proxies): cache for performance and
bandwidth savings, often marked as public.
• Server-side caches (application or data stores like Redis/memcached): cache data to serve
repeated requests quickly at the origin.
Each cache uses the same HTTP rules (headers) to decide if and how long to keep a copy.
Cacheable
Some caching HTTP Headers in the response:
Cache-Control (most important)
• What it does: Directs caching behavior for both browsers and intermediate caches.
• Key directives:
• public: cacheable by any cache (including shared caches like CDNs)
• private: cacheable only in a browser, not by shared caches
• max-age=seconds: freshness lifetime
• no-store: do not cache
• Examples:
• Cache-Control: public, max-age=600
• Cache-Control: private, no-store
• Cache-Control: public, max-age=3600, s-maxage=600
Uniform Interface
REST is defined by 4 interface constraints:
• Identification of resources.
• Manipulation of resources through representations
• Self-descriptive messages
• Hypermedia as the engine of application state.
Uniform Interface
You use the URI (Unique Resource Identifier) standard to uniquely identify a resource.
Example domain: Library/Books API
• Resource URIs (examples)
• /books -> collection of all books
• /books/{isbn} -> a specific book identified by ISBN
• /books/{isbn}/reviews -> reviews for that book
• /authors/{authorId} -> a specific author
• /authors/{authorId}/books -> books written by that author
Manipulation of resources through representations
• The state of a resource is sent to and from the client as a representation (usually JSON or XML).
• Clients use HTTP methods to create, update, or delete that resource by sending
representations, and servers store the resulting state.
We shouldn’t use a POST method to delete a resource for example.
We don’t need to name the URIs as: getBooks, we simply need to use the HTTP get method on
the books URI: GET /Books
Self-descriptive messages
Every request and response should carry enough information (via headers, status codes, and
body) for a client to understand what happened and what to do next, without needing extra
outside instructions.
What it includes:
• Method and status: HTTP method (GET, POST, etc.) and status codes (200, 404, 500, …) tell you
the action and the result.
• Headers: tell you how to interpret the body (Content-Type, Content-Length), how to cache
(Cache-Control), how to validate (ETag, Last-Modified), how to redirect (Location), how to
authenticate (WWW-Authenticate), and more.
• Body (representation): the actual data (usually JSON or XML) that describes the resource or
error.
Hypermedia as the engine of application state (HATEOAS)
The server’s responses include links to related resources and possible next actions, so the client
can navigate the API by following those links instead of constructing URLs itself.
Pros:
• Better client-server decoupling; UI can adapt if URLs change.
• Easier to evolve APIs without breaking clients.
• Improved navigability and self-describing responses.
Cons:
• Adds complexity to API design and responses.
• Payloads can be larger due to extra links.
Layered System
An architecture built in layers. Each layer talks only to the one next to it. The client (UI) talks to the
top layer, which talks to the next, and so on, until data is stored in the database.
• The client is the UI (in a browser or app) and often uses a frontend framework (like React, Vue,
or Angular) to render what you see.
• The server provides data and logic through APIs (not HTML). The UI framework takes that data
and displays it.
Pros:
• Clear separation of concerns: UI work stays in the client layer; data/logic stays in the server
layer; data storage stays in the database.
• Reuse across clients: The same API can serve web, mobile, and other services without
duplicating business logic.
• Independent scaling: You can scale the user interface separately from the API and the
database based on demand
Code On Demand (Optional)
An optional constraint that lets the server send executable code to the client to extend its
functionality. It’s optional and most useful for UI customization or plugins in a frontend app, but it
brings security and performance trade-offs.
Modern Frontend Frameworks now days offer a comprehensive list of features that makes relying
on code from the server less and less needed.
Maturity of a REST API
In an ideal world, we would implement all the mendatory REST constraints.
But in reality, this is not the case.
For that we define maturity levels of a REST API
LEVEL 0
Level 0 — The Swamp (RPC over HTTP)
What it means:
• HTTP is just a transport. You don’t model resources with URLs or HTTP semantics, you invoke
actions via a payload.
Example:
• Request to get the book with ID 42: POST /api with body { "action": "readBook", "id": 42 }
LEVEL 1
Level 1 - Resources
What it means:
• Exposing resources via different URLs instead of using one single URL for everything. But still not
fully using the full potential of HTTP Verbs.
Example:
• Request to update a book (non-HTTP-semantic): POST /updateBooks/42 with body { "title": "New
Title", "year": 2009 }
LEVEL 2
Level 2 - Methods
What it means:
• The API uses HTTP methods to express actions on resources, with correct status codes.
Example:
• Read a book: GET /books/42 -> 200 { id: 42, title: "...", author: "...", year: 2008 }
• Create a book: POST /books with body {"title": "...","author":"...","year":2008} -> 201 Created,
Location: /books/43
• Update a book: PUT /books/42 with body { "title": "...", "year": 2009 } -> 200 or 204
• Delete a book: DELETE /books/42 -> 204 No Content
=> We are using Resources with the correct HTTP method and return type.
LEVEL 3
Level 3 - Hypermedia as the engine of application state (HATEOAS)
What it means:
• Responses contain hypermedia controls (links) that tell the client what it can do next, and
where to go next.
Examples:
GET /books/42 returns a response with links:
SOAP VS REST
SOAP REST
Acronym Simple Object Access Protocol REpresentational State Transfer
Core Idea A protocol (Imposes how you do An architectural style (Set of rules)
things)
Message XML Based envelopes Flexible: Commonly JSON but it can be XML or
Format anything else
Example: Operation: GetBook Resource: /books/42
GET books HTTP method: POST HTTP method: GET
Request: GET /books/42
Response: 200 Status
REST Specification:
Open API
OPEN API
As we develop an API and publish it, people will start consuming it, for that we need to provide an
Interface contract for consumers that provide:
• What does each endpoint do.
• what are the requested parameters.
• what does each endpoint return.
=> This is called API Specification (Definition).
As SOAP is a standardized protocol, it has its own API Specification language named WSDL (Web
Services Description Language).
As REST is not a protocol, it didn’t come with its own standardized language for API Specification
as multiple solutions existed (RAML, API Blueprint, …), but in now days, OPEN API became a “de
facto” standard for REST APIs.
Naming Confusion: OPEN API VS SWAGGER
You will often hear the terms OPEN API and SWAGGER used interchangeably.
History:
2010: Tony Tam at Wordnik created Swagger, a family of tools (swagger-ui, swagger-gen, …) that
provides an API specification for REST.
2016:
• OpenAPI Initiative forms under the Linux Foundation.
• By that time Swagger was commonly used so the OpenAPI used Swagger Specification.
• Relationship becomes: OpenAPI Specification is the formal contract; Swagger continued to exist
as an ecosystem of tools that implements and uses it.
=> OpenAPI spec (the contract): defines what the API should do, in a machine-readable way.
Swagger tooling (the implementation of that contract in tools): provides docs, codegen, mocks,
and test workflows around that contract.
Writing Open API Specs
OpenAPI file is written in YAML or JSON. For each endpoint
of the API it describes things like:
• The path.
• A summary of what the method does.
• The HTTP method used.
• The methods inputs (path/query/body).
• Responses (The possible status codes (201, 400, 404,
…) and bodies).
Exercise 1
We have an existing Swagger application ([Link]
We will code together a new endpoint.
You will be provided with an open api spec file that is not complete.
You are asked to add the open api specification for the newly created endpoint.
Generating open API file automatically
Writing Open API specs yourself is a tedious task as it’s repetitive and error prone.
All programing languages do support libraries that can automatically generate open API
specification file based on your backend code:
Java:
Springdoc OpenAPI: auto-generates OpenAPI from Spring controllers and models.
• MicroProfile OpenAPI (SmallRye): similar idea for MicroProfile apps.
• Quarkus: Uses SmallRye OpenAPI (Implementation of the MicroProfile OpenAPI) extension to
surface the OpenAPI document.
.NET
[Link]: generates OpenAPI from [Link] Core controllers.
[Link] / TypeScript
NestJS with @nestjs/swagger: decorators generate OpenAPI.
swagger-jsdoc + swagger-ui-express: JSDoc comments drive the OpenAPI JSON.
Python
FastAPI: OpenAPI is generated automatically from Python types.
What we can do with Open API specification
Now that we have a file containing the OPEN api specification of our backend, we can do a lot of
things with it:
Documentation and discovery
• What you get: interactive, browsable docs you can explore and try out.
• Tools: Swagger UI, Redoc, ReDocly.
Client code generation
• What you get: ready-to-use client libraries in many languages.
• Tools: OpenAPI Generator, Swagger Codegen (older).
Exercise 2
We have an existing Swagger application ([Link]
We want to add a new endpoint to it (Delete).
1. Code the solution in the Quarkus Resource.
2. Generate the open API spec file for it automatically.
3. Generate a typescript client from that class.
4. Launch the quarkus server locally.
5. Access the Swagger-ui URL.
6. Test the endpoint using swagger-ui locally.
7. Test the endpoint using a tool of your choice (cURL, Postman).
PS: check the slack chat to properly set the remote with the token.
Than ks fo r your
atten tion