0% found this document useful (0 votes)
4 views

API+Design

The document outlines best practices for RESTful API design, including creating a data model, defining resources, and determining HTTP methods. It emphasizes the importance of resource naming conventions, URI structure, and handling special behaviors like pagination and long-running requests. Additionally, it covers API security considerations, including authentication and input validation techniques.

Uploaded by

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

API+Design

The document outlines best practices for RESTful API design, including creating a data model, defining resources, and determining HTTP methods. It emphasizes the importance of resource naming conventions, URI structure, and handling special behaviors like pagination and long-running requests. Additionally, it covers API security considerations, including authentication and input validation techniques.

Uploaded by

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

REST API Design

RESTful API design

• Create Data Model


• Derive Resources
• Decide on Representations
• Name Resources by URL
• Determine HTTP methods
• Determine special behavior
• Consider errors
Data Model

Specified in any conceptual


Purpose
data modeling language:
• entity-relationship model • Specify properties of
• UML resources in an abstract
manner (implementation
independent)
Data Model

Payment

Customer

Account Limits

Balances
Resource Model

Atomic resources
• Entities of data model exchanged as a whole

Collection resources
• Atomic resources grouped into a set
• Grouped entity
• Scoped or not

Composite resources
• Different resources seen as a whole
• Collectively retrieved or deleted (e.g. accounts and balances)

Controller resources
• Complex logic that involves processing multiple resources

Processing function resources


• Processing particular resources
• Resource independent processing
Relationships

Atomic resource
• No traversal of associated relationships
• Directly available via API

Collections:
• First class – directly available (e.g. customers)
• Scoped – makes sense only as children of other resources (ex. Limits, balances)
Resource URIs

{scheme}://{host}/{base-path}/{path}[?{query-string}]

Naming

• Atomic resources – singular nouns


• Collections – plural nouns
• Controllers – verbs

Scheme

• HTTP, HTTPS, HTTP+HTTPS

Host

• Domain of API
Base Path

/{feature}/[ {sub-feature}/ ]/{version}

Feature
Higher level functionality Groups related functionality

Sub-feature
Specific functionality

Versioning
Patch version increase Minor version increase Major version increase
Ex. v{major}.{minor}.{patch} • API unchanged, implementation changed • New features, backward compatible • API changed fundamentaly
Path

URI templates
• /customers/{customer-id}/accounts/{account-number}
• Strings in {} are variable substituted by actual values
• Individual members of the collections
• /customers/1001
• /customers/1001/accounts/ROBNK19992929223323/limits/128
• Indicates relationship between entity types

Query String
• Part of URI contributing to the unique identification of a resource
• URI w/ QS != URI w/o QS
Format in which instances of the entity
types in the data model are exchanged

Resource Entity -> Data structure ->


Representat rendering/representation
Ex. JSON, XML
Representation !
= data structure

ion

Specified by MIME (Multipurpose Internal


Mail Extensions)
HTTP Methods

Manipulation of resources:
GET, POST, PUT, DELETE, OPTIONS etc.

Effects of requests:
Safe - multiple invocations no effect/change on Idempotency - multiple invocations only the first
target resource invocation has effect on the resource
GET <atomic resource URI>
<collection URI> {filter}

No message
Safe Idempotent
body
PUT <resource URI>

Substitutes the resource


Idempotent but not safe

Message body
Modified and complete representation of resource

May create a resource if it doesn’t exist but should be avoided


POST <collection resource URI>
<controller URI>

Usage Message body Response


• Create a new • Representation of • Location header –
resource resource URI of the new
• Trigger resource
function/controller
Deletes resource
DELETE
<resource
URI> Idempotent First run 200
OK
request, but in 2nd run 404
practice NOT FOUND
Headers

Transport non-functional properties


Accept
• Acceptable content types for the client

Authorization
• Credentials of the client for authentication by the server

Content-Type
• MIME type of the content body for PUT or POST

Request If-Match

Headers
• Concurrency control; client-passed entity tag == server tag request is
performed

If-Modified since
• Avoid retrieve cached data in client side based on timestamp

If-None-Match
• Avoid retrieve cached data in client side based on tag

If-Unmodified-Since
• Concurrency control based on timestamp
Current-Location
• URI of the message body, e.g. status of long-running
request

Content-Type
• MIME type of message body

Response ETag
Headers • Fingerprint of the resource as found on server (digest)

Last-Modified
• Timestamp of the last modification on server

Location
• Location of a newly created resource
Status Codes

200 OK • Request was successful, message body contains the result

201 Created • Request was successful; URI of newly created resource is in Location header; ETag + message body

202 Accepted • Processing started and in progress; Content-Location indicates URI of status resource (can be retrieved with GET)

303 See Other • Response is available at other URI given by Location header, e.g. after long running request

304 Not Modified • Returned in response of a conditional GET (If-Non-Match, If-Modified-Since) when conditions are not met

404 Not Found • Request resource does not exist

406 Not Acceptable • Media type not supported (GET with Accept not supported by server)

412 Precondition Failed • Conditional request condition not met (If-Match, If-Unmodified-Since)

415 Unsupported media type • Request body in format not supported by server
Special Behavior

Content
Queries Pagination
Negotiation

Concurrency Long running


Client side caching
control requests

Security (see
Error reporting Oauth2, OpenId-
connect slides)
Content Negotiation

Resource != representation

Server driven
• Client specifies capabilities (Accept ) in request
• Server determines best representation and replies

Client driven
• At first request Server detects multiple representations and replies with 300 Multiple Choices
• Client selects one and puts it in the following request and obtains it form server

GET /accounts/ROBRZ001234
Accept: application/json;q=0.9, application/xml;q=0.1

If not supported either, then server returns 406 Not Acceptable


Queries

Filter

• Boolean expression made with attributes from the entity type


• Filter=(type=“ATM withdrawal” AND amount>100)

Sort

• Expression with list of attributes and sort indication


• Sort=(amount DESC, date-executed ASC)

Projection

• Subset of the entity’s attributes


• Projection=date,location,amount

Easy filtering

• URL based
• GET /transactions?status=new&sortDesc=amount

Complex Filtering

• Controller
• POST /transactions/search HTTP/1.1
• Filter=
• Sort=
• Projection=
HATEOAS and Pagination

{
"accountId": "123",
• Hypermedia as the Engine of Application State
"iban": "ROBRX0000111",
• Self describing API "type": "current"
"links": [{
• Rel
"rel": "self",
• Relationship
"href": "http://localhost:8080/mybank/api/customers/101/accounts/123"
• Self etc. }, {
• Href "rel": "balances",
• Complete URL to perform action or navigate "href":
"http://localhost:8080/mybank/api/customers/123/accounts/123/transactions"
• Pagination }, {
• Links: next, prev, first, last "rel": "owner",
• Filter by offset and limit "href": "http://localhost:8080/mybank/api/customers/123"
}
}
Long Running Requests

More than a few seconds

• long running process (possibly with manual intervention)


• processing takes a long time

Steps

• POST to function/controller
• Server responds with 202 Accepted + Content-Location URI of a “job”resource
• GET on “job”resource URI returns 200 OK + processing status
• When job finished, GET will return 303 See Other with Location header with the result resource
• GET on result resource retrieves the actual result of the long running process

Alternative

• Client provide callback URI in request, when long running process is finished, server will post the result at the indicated location
Standards for
API design
• Open API v2 – Swagger (widely used and
supported)
• https://swagger.io/docs/specification/2
-0/basic-structure/

• Open API v3
• https://swagger.io/specification/

• Approaches
• API first
• Code first (exercise)
API Security Considerations

Main idea

• API Gateway is at the core of enforcing security

Traditional approach:

• firewall

API security:

• analyzes messages, tokens and parameters


1wTLS server
authentication
Transport security 2wTLS mutual
authentication

API Application data


Protects data in
Security - transit
Authentication and
authorization data:
Credentials,

HTTPS
tokens, API keys

Data integrity
API Security – Identity and Access

Authentication Access Control Identity Provider


Access tokens Json Web Tokens OAuth2
OpenID Connect
API Security – Input Validation

VALIDATE INPUT USING STRONG TYPES CONSTRAIN STRING REJECT LIMIT REQUEST SIZE LOG INPUT VALIDATION
IN API PARAMETERS INPUTS WITH REGULAR UNEXPECTED/ILLEGAL FAILURES
EXPRESSIONS CONTENT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy