0% found this document useful (0 votes)
13 views68 pages

API Design Principles Explained

The document outlines key principles of API design, emphasizing the importance of effective communication, reusability, and innovation in API development. It discusses what constitutes a 'good' API, various design patterns, and the significance of resource relationships and identifiers. Additionally, it covers collective operations, safety, and security measures necessary for robust API architecture.

Uploaded by

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

API Design Principles Explained

The document outlines key principles of API design, emphasizing the importance of effective communication, reusability, and innovation in API development. It discusses what constitutes a 'good' API, various design patterns, and the significance of resource relationships and identifiers. Additionally, it covers collective operations, safety, and security measures necessary for robust API architecture.

Uploaded by

karimi.amir96
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

API DESIGN

PRINICIPLES
Professor:
Dr. Ashtiani

Presenter:
Mohammad Ghafghazian
Mahdi Eshraghi Nejad

Software Architecture Fall 1403


Fundamentals &
Resource
Relationships

Core Principles Collective operations

Introduction Safety &


Security
Table Of
Contents
01
Introduction
What are APIs?
❑ An API defines the way in which computer
systems interact.
❑ API that is built to be exposed over a
network(web API) and used remotely by lots
of different people.
Why do APIs matter?

Enable Communication Enhance Reusability

Drive Innovation Simplify Integration


What makes an API “good”?
❑ Operational
It must do the thing users actually want.
❑ Expressive
Allows users to express the thing they want to do clearly and
❑ Simple
One of the most important things related to the usability of any system is
simplicity.
❑ Predictable
Easy to understand without needing extensive documentation
What are API design patterns
❑ Software design pattern is what happens when a particular design
can be applied over and over to lots of similar software problems,
with only minor adjustments to suit different scenarios.
❑ API design pattern is simply a software design pattern applied to
an API rather than all software generally.
❑ API design patterns are reusable solutions to common problems
encountered during API development.
Why are API design patterns important?

❑ API design patterns are essential tools for


building robust, scalable, and user-friendly
APIs.

❑ By understanding and implementing these


patterns, developers can create APIs that
not only meet the needs of their users but
also adhere to best practices in the
industry.
Anatomy of an API design pattern

Name and synopsis Motivation Overview

The name will be descriptive Explains the problem the Provides a high-level
enough to convey what the pattern addresses and why it’s description of the pattern,
pattern is doing, but not so needed, providing context for summarizing its structure
long. its purpose. and purpose.

Implementation Trade-offs

Details the steps, components, Highlights the benefits and


and techniques needed to apply drawbacks of using the pattern,
the pattern effectively helping to evaluate its
suitability
02
Core Principles
API Naming
❑ In the world of software engineering generally, it’s practically
impossible to avoid choosing names for things.
❑ What makes a name “good”?
1. Expressive
2. Simple
3. Predictable
What is resource layout?

❑ When we talk about resource layout, we generally mean the arrangement of


resources in our API, the fields that define those resources, and how those
resources relate to one another through those fields.
❑ In other words, resource layout is the entity (resource) relationship model
for a particular design of an API.
❑ If you’ve ever designed a relational database with various tables, this should
feel familiar: the database schema you design is often very similar in nature
to how the API is represented.
Types of relationships

❑ Reference Relationships: The simplest way for two resources to relate to one another is
by a simple reference. By this, we mean that one resource refers to or points at another
resource.
Types of relationships

❑ Many-To-Many Relationships: Like a fancier version of references, a many-to-many


relationship represents a scenario where resources are joined together in such a way that
each resource points at multiple instances of the other.
❑ For example, if we have a ChatRoom resource for a group conversation, this will obviously
contain lots of individual users as members. However, each user is also able to be a
member of multiple different chat rooms.
Types of relationships

❑ Self-Reference Relationships: As the name hints, in this relationship a resource points to


another resource of the exact same type, so the self refers to the type rather than the
resource itself.
Types of relationships

❑ Hierarchical Relationships: Hierarchical relationships are sort of like one resource having
a pointer to another, but that pointer generally aims upward and implies more than just
one resource pointing at another.
❑ Unlike typical reference relationships, hierarchies also tend to reflect containment or
ownership between resources
Entity relationship diagrams
These two lines on the
connection are used to
represent that each
student will only ever be
enrolled in one school.

Has Has
one many

This angled end on the


connection means that
each school will
have many students
enrolled.
Resources for everything Deep hierarchies
when actions or processes are overly nested resource
unnecessarily modeled structures in APIs, making
as resources. endpoints long, complex, and
hard to use.
Relationship
Anti-patterns
In-line everything
where related or Overloading Endpoints
reusable data is where a single API endpoint is
embedded directly into API used to handle multiple
responses instead of being unrelated actions or data types.
referenced as separate resources
Deep hierarchies example
Data Types
❑ When designing any API, we always have to think of the
types of data we want to accept as input, understand, and
potentially store.
Data Types
o Booleans o Enumerations
interface Person { enume Color {
id: string; Brown = 1;
isStudent: Bool; Black = 2;
} }
o Numbers o Lists
interface Person { interface Book {
id: string; id: string;
nationalCode: Int; title: string;
} categories: string[];
o Strings }
interface Person { o Maps
id: string; Interface SecurirtyConfig
interface ChatRoomGroup { {
name: string;
id: string; password: string;
}
name: string; requiredPassword:
securityConfig: SecurirtyConfig; bool;
} }
03
Fundamentals & Resource
Relationships
Introduction
In this chapter, we’ll explore resource identifiers
in-depth. This includes what they are, what
makes for a good one (and a bad one), as well as
how they can be used in your APIs
What is an identifier?
❑ In short, identifiers give us a way to uniquely address and talk about
individual resources in an API.
❑ In more technical terms, these identifiers are chunks of bytes (usually
a string value or an integer number) that we can use as the way we
point to exactly one resource in a resource collection.
❑ In other words, these identifiers are used to address a single resource
among some larger collection of resources.
Identifier Example

Resource Query
host service type params

[Link] ?fields=name

version Resource
identifier
4. Fast and easy to generate
should be simple and efficient to create,
avoiding complex calculations or dependencies

3. Permanent 4 5. Unpredictable
API identifiers should remain stable should be difficult to guess, especially for
over time, avoiding changes.
3 5 sensitive resources

2. Unique What makes a


Represent a single resource or entity, good 6. Readable, shareable,
avoiding ambiguity or overlap 2 identifier? 6 and verifiable
should be human-readable, easy to share
in URLs or logs, and structured to allow
quick validation of their correctness
1. Easy to use
Simple for developers to understand and
use them without extensive documentation
1 7
7. Informationally dense
should encode relevant context about the
resource
Standard methods

Name Behavior Example

Get Retrieves an existing resource GetChatRoom()

List Lists a collection of resources ListChatRooms()

Create Creates a new resource CreateMessage()

Update(patch) Updates an existing resource UpdateUserProfile()

Delete Removes an existing resource DeleteChatRoom()

Replace(put) Replaces an entire resource ReplaceChatRoom()


Partial retrieval
❑ Partial retrieval in API design refers to fetching only
specific fields or subsets of data from a resource, rather
than the entire dataset.
❑ This allows clients to request and receive just the data
they need, improving performance and reducing payload
size.
❑ Benefits: Improved Efficiency, Customizable Responses,
Reduced Overhead
Partial update
❑ Partial update in API design refers to updating only
specific fields of a resource rather than replacing the
entire resource.
❑ This allows clients to modify only the necessary data,
improving efficiency and minimizing the risk of
overwriting data unintentionally.
❑ Benefits: Minimized Data Transfer, Improved
Performance, Reduced Risk of Data Loss
Long-running operations (LRO)

❑ In most cases, incoming requests can be processed quickly, generating a


response within a few hundred milliseconds after the request is received.
❑ In the cases where responses take significantly longer, the default
behavior of using the same API structure and asking users to “just wait
longer” is not a very elegant option.
Long-running operations (LRO)
❑ LROs refer to tasks or processes in an API that take a significant
amount of time to complete.
❑ These operations typically involve complex calculations or large data
processing, that can cause delays.
❑ These tasks may take seconds, minutes, or even hours to complete,
depending on their nature.
❑ Example: Generating reports, backup, Complex data analysis.
Resource relationships

❑ Singleton sub-resources
❑ Cross references
❑ Association resources
❑ Add and remove custom methods
❑ Polymorphism
Singleton Sub-Resources

Manage large or Ensure different Reduce write conflicts


complex components security or access for frequently updated
separately requirements data
Cross References:

❑ A reference from one resource to another using a unique

identifier (e.g., UserId).

Purpose:

❑ Enables resources to interact without duplication.

❑ Allows referencing local or global resources.


Association Resources

1 2 3 4
Standard
Definition: Standard
Benefits: Methods:
❑ Separate Methods:
• Explicitly ❑ Create: Adds a
resources that ❑ List: Retrieves
address relationship
represent all
relationships. (e.g., adding a
relationships relationships
• Store user to a
between two ❑ Optional
metadata group).
resources. methods:
about ❑ Delete:
Aliases for
relationships Removes a
convenience
relationship.
Add and remove custom methods

1 2 3 4
Definition: Definition: Advantages: Disadvantages:
❑ A lightweight ❑ Use add and ❑ Simpler and more ❑ Cannot store
alternative to remove methods intuitive API. metadata about
association instead of creating ❑ No need for relationships
resources for separate additional ❑ Requires
managing many- association resources. choosing a
to-many resources "managing
relationships. resource"
Polymorphism
A design approach where resources
share a common structure but
represent different types

Benefits: Trade-offs:
❑ Reduces ❑ Complexity in
duplication by validation for
unifying subtype-
similar specific fields.
resources ❑ Risk of errors
under a single if invalid fields
interface. are provided
❑ Simplifies API
methods
04
Collective operations
Collective operations
❑ Copy and move
❑ Batch operations
❑ Criteria-based deletion
❑ Anonymous writes
❑ Pagination
❑ Filtering
❑ Importing and exporting
Copy and Move

Creates a Relocates a resource


duplicate of a to a new parent or
resource renames it

? Handling hierarchical resource


relationships

Safe renaming and relocation of


resources ?

?
Atomicity and consistency during
operations
Implementation of Copy and Move

Java Scripts

abstract class ChatRoomApi {


@post("/{id=chatRooms/*/messages/*}:move")
MoveMessage(req: MoveMessageRequest): Message;

@post("/{id=chatRooms/*}:copy")
CopyChatRoom(req: CopyChatRoomRequest): ChatRoom;
}
Batch Operations:

Perform operations on multiple resources simultaneously.

Reduces the need for repetitive API calls.

Motivation:

Ensure atomicity across resource groups.

Avoid partial successes or failures.


Implementation of Batch Operations

Java Scripts

abstract class ChatRoomApi {


@post"/chatrooms:batchDelete")
BatchDeleteChatRooms(req:BatchDeleteChatRoomsRequest):void;

}
Criteria-Based Deletion
1 2 3
Risk of Over-Deletion: Consistency: Address Atomicity: Guarantee
Ensure criteria are resource dependencies complete success or
precise to avoid and relational integrity failure of deletion
accidental data loss

Advantages
1 2
Simplifies large-scale Reduces need to fetch
deletions and filter resources
beforehand
Anonymous Writes in APIs

1 1
Security: Prevent misuse or
Limit access and operations
spam attacks (e.g.,
for anonymous users
CAPTCHA, rate limiting)

2 2
Ownership: Assign
Log anonymous writes for
ownership after
monitoring and debugging
authentication if needed

3 3
Validation: Ensure data Use clear documentation to
integrity while accepting set user expectations
anonymous submissions
Pagination
Definition Use Cases Benefits

❑ Displaying
Breaks down large search results, ❑ Improves API
datasets into user lists, or response
smaller, activity logs. times.
manageable parts ❑ Reducing ❑ Simplifies
(pages). response size handling of
for improved large datasets.
performance.
Filtering
Definition:
1 Enables clients to retrieve specific data by applying
conditions on resources.

Benefits:
2 ❑ Reduces data transfer by only returning relevant
results.
❑ Improves performance and user experience.

❑ Challenges:
3 ❑ Performance: Complex filters can strain the backend.
❑ Validation: Ensure filters are safe and correctly
parsed.
Importing and Exporting

1 2 3
Use Cases:
Definition: ❑ Importing: Migrating Challenges:
❑ Importing: Uploading datasets, integrating ❑ Size Limits: Managing
external data into the with external systems. memory for large files.
system. ❑ Exporting: Backups, ❑ Error Handling:
❑ Exporting: Retrieving analytics, or sharing Detecting and logging
data in bulk from the data with third-party invalid records during
system for external use. tools. import.
05
Safety & Security
Safety & Security
❑ Versioning and compatibility
❑ Soft deletion
❑ Request deduplication
❑ Request validation
❑ Resource revisions
❑ Request authentication
Why Versioning Matters?

APIs evolve over time; changes must not disrupt users.


❑ How to introduce changes without breaking existing
functionality?
❑ What strategies exist for managing versioning effectively?
What is Compatibility?
The ability of different API versions to work together.
Backward Compatibility:

Changes are made without breaking existing code.

Challenge:

Balancing new functionality with preserving old behavior.


Common Versioning Strategies

1 2 3
Perpetual Agile Semantic
Stability: Instability: Versioning:
Each version Limited number Uses numbers
remains stable; of versions, older (e.g. 1.2.0)
new versions ones deprecated
contain breaking quickly
changes
Soft Deletion
Prevents accidental
or unintended data
loss
1
2 Allows easy
recovery of deleted
resources

between hard deletion


and data retention
3
Provides a middle ground
Implementation and Key Considerations

list delete get

Handling referential Defining clear rules for


integrity (e.g., when undelete and expunge
deleted resources are operations
referenced by others)

undelete expunge
Request Deduplication

Request deduplication ensures that repeated API requests do


not lead to duplicate or unintended actions

Double
Multiple Redundant
charges in
resource job
payment
creations executions
systems
How Request Deduplication Works

Client Server
Side Side

Check if the identifier exists:


Generate a unique ❑ If yes: Return the
identifier (e.g., UUID previously stored result.
or hash) for each ❑ If no: Process the request
and store the result
request
along with the identifier.
Storage Management:
Efficiently storing request identifiers
Reliability: APIs handle retries
without introducing errors. and results.
Consistency: Avoids unintended Concurrency: Ensuring no race
duplicate actions. conditions with simultaneous
duplicate requests.
User Confidence: Prevents
issues like double billing. Expiration Policies: Defining
when stored identifiers should expire
to manage resources effectively.
Request Validation

1 2 3 4
Data types: Ranges and
Required Custom
Ensures data sizes:
fields: constraints:
matches expected Limits numbers,
Ensures necessary Specific business
formats (e.g., string lengths, and
data is included. logic validations.
string, integer). array sizes.
Implementing Request Validation
1 2 3 4
Validation Layers Error Handling Tools & Frameworks Testing Validations:

❑ Implement ❑ Provide clear, ❑ Leverage


user-friendly ❑ Use
validation at validation
error messages automated
both the when validation libraries like
client-side JSON tests to
fails.
(optional) ❑ Use standard Schema or ensure all
and API HTTP status
frameworks validation
codes (e.g., 400
server-side with built-in rules are
for bad
(mandatory). requests). support. enforced.
For tracking changes made by users

Allows users to revert mistakes

Helps in resolving updates from


multiple sources
Implementing Resource Revisions

1 2
Revision Storage: Version Conflicts:
❑ Store revisions as separate ❑Detect and resolve
entries in a revision history conflicts when concurrent
table. updates occur.
❑ Include metadata like ❑Use strategies like last-
timestamps and the user writer-wins or manual
making the change. merging.

3 4
Retrieving Revisions:
❑ Provide endpoints to Automation:
fetch the full revision ❑ Automatically
history. capture revisions
❑ Allow retrieving or whenever changes
restoring specific occur to a resource.
revisions.
Request Authentication

JWT (JSON Basic


API Keys OAuth 2.0 Web Authentic
Tokens) ation

unique tokens
Allows secure Encodes user
used to Uses username
access via tokens, data in a token
authenticate and and password
suitable for for stateless
authorize API (less secure)
delegated access authentication
access
Request Authentication
Use HTTPS
Encrypt all API traffic to prevent eavesdropping or tampering

Token Expiry
Set short expiration times for tokens to minimize risks

Rate Limiting
Apply rate limits per authenticated user to prevent abuse

Error Responses
Use standard status codes (e.g., 401 Unauthorized, 403 Forbidden).

Logging and Monitoring


Track authentication attempts and flag suspicious activities
Thanks!
Do you have any
Slidesgo

CREDITS: This presentation template was created by Slidesgo, and


Flaticon Freepik

includes icons by Flaticon, and infographics & images by Freepik

questions?!

You might also like