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

API Design Concept

This document provides guidelines for API design at Hub IT, including core principles like API-first development and versioning. It covers best practices for API design, consistency, references and hypertext, security, implementation, and using API gateways. It also provides instructions for creating OpenAPI specifications for documenting APIs.

Uploaded by

radujse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
162 views

API Design Concept

This document provides guidelines for API design at Hub IT, including core principles like API-first development and versioning. It covers best practices for API design, consistency, references and hypertext, security, implementation, and using API gateways. It also provides instructions for creating OpenAPI specifications for documenting APIs.

Uploaded by

radujse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

API Design Concept

API and Services at Hub IT

Exported on Jun 06, 2018


API and Services at Hub IT – API Design Concept

Table of Contents

1 Approval state: approved (v57) .......................................................................................... 4


2 Introduction .......................................................................................................................... 5
2.1 How to read this document ................................................................................................. 5
2.2 Structure ............................................................................................................................. 6
3 Core Principles ..................................................................................................................... 7
3.1 API First .............................................................................................................................. 7
3.2 Language ............................................................................................................................ 7
3.3 Versioning ........................................................................................................................... 7
3.4 Provisioning APIs ............................................................................................................... 8
3.4.1 API Gateway provisioning ................................................................................................................. 8
4 API Design ............................................................................................................................ 9
4.1 Design Outside-in ............................................................................................................... 9
4.2 Follow REST semantics ..................................................................................................... 9
4.3 PATCH and PUT request methods .................................................................................. 10
4.3.1 PUT & PATCH Examples :.............................................................................................................. 11
4.4 Status Codes .................................................................................................................... 12
4.5 Content-Type .................................................................................................................... 12
4.6 Data Types ....................................................................................................................... 12
4.7 Data Type Extensibility ..................................................................................................... 13
4.8 Minimal APIs ..................................................................................................................... 13
4.9 Handling Asynchronous or Long Running Tasks - Process Tracking .............................. 13
4.10 Service and API Granularity ............................................................................................. 15
5 Consistency Fundamentals .............................................................................................. 17
5.1 URL Structure and Versioning .......................................................................................... 17
5.2 Handling URL Length and lengthy Query Parameters ..................................................... 17
5.3 Reserved resource ids naming in URL path..................................................................... 17
5.4 Time and Date format ....................................................................................................... 18
5.5 Request Headers .............................................................................................................. 18
5.6 Response Headers ........................................................................................................... 19
5.7 Error Model ....................................................................................................................... 19
5.7.1 processing errors ............................................................................................................................ 19
6 References and Hypertext ................................................................................................. 22
6.1 General Relations ............................................................................................................. 22
6.2 Paging Relations .............................................................................................................. 22
6.3 Filtering ............................................................................................................................. 23
7 API Security ........................................................................................................................ 24
8 API implementation and development ............................................................................. 25
8.1 Use Appropriate Status Codes ......................................................................................... 25
8.2 Robust Implementation..................................................................................................... 25
8.3 Event Driven Design ......................................................................................................... 25
8.4 Guaranteeing “exactly once” semantics ........................................................................... 25
9 API Gateway usage - OpenAPI and LHMDW ................................................................... 27
9.1 Summary .......................................................................................................................... 27
9.2 Introduction ....................................................................................................................... 27
9.2.1 Classification of this document........................................................................................................ 27
9.3 Scope................................................................................................................................ 27
9.4 API Gateways ................................................................................................................... 27
9.4.1 LH Open API Gateway .................................................................................................................... 27
9.4.2 LH MDW Internal Gateway - Zambas R6 ........................................................................................ 28
9.5 API Management .............................................................................................................. 28
9.5.1 Rate Limiting ................................................................................................................................... 28

Table of Contents – 2
API and Services at Hub IT – API Design Concept

9.5.2 Throttling ......................................................................................................................................... 28


9.5.3 Security (#TODO Security is an open Topic w. GI/X)...................................................................... 28
9.5.4 Open API Gateway OAuth Scope and User Context support ......................................................... 29
9.6 Logging and Troubleshooting ........................................................................................... 30
9.7 Caching............................................................................................................................. 30
9.7.1 Open API Gateway Caching capabilities......................................................................................... 30
10 How to create Swagger v2.0/API Spec ......................................................................... 31
10.1 Swagger v2.0 template ..................................................................................................... 31
10.2 Metadata (Swagger version, Info) .................................................................................... 32
10.3 Base URL ......................................................................................................................... 33
10.4 Security Definitions ........................................................................................................... 33
10.4.1 Fixed Fields ................................................................................................................................. 33
10.5 consumes, produces ........................................................................................................ 34
10.6 Paths ................................................................................................................................. 35
10.7 Parameter Types , Request, Response, Definitions (Input Model) .................................. 37
10.8 Request (Input Model) ...................................................................................................... 39
10.9 Responses (Output Model)............................................................................................... 40
10.10 Examples (Input & Output Model) ................................................................................. 42
10.11 Schema Examples ........................................................................................................ 42

Table of Contents – 3
API and Services at Hub IT – API Design Concept

1 Approval state: approved (v57)


Concept for API Design within Lufthansa Group Hub IT.
Document version: 59

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 4
API and Services at Hub IT – API Design Concept

2 Introduction
This document shall help you to create decent APIs within the LH Group organization. It applies
to APIs created within the LH Group with full control over the API contents. If products are
incorporated which already offer APIs, this document is not applicable. There are a lot of
philosophical discussion on what is RESTful and what is good API Design. Let's keep the things
practical and stick to the rules below.
We are open for discussion, we aim at having some consistency on technical and design level
to ease creation and operation of APIs as well as their consumption.
Most of the concepts listed have been heavily inspired and sometimes blatantly copied from
existing resources, such as the API guidelines from Zalando and Adidas.
According to the LH Group architecture framework, this document is classified as a concept and
applies to all new projects and products developed within the Lufthansa Group.

Policy

Target Architectures, Concepts & Rules

Guidelines, Patterns & Best Practices

2.1 How to read this document


The CAPITALIZED words throughout these document have a special meaning:
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in
this document are to be interpreted as described in RFC2119.
See RFC2119
Some areas of this concept are under discussion or require rework. Mark those items using
"(#TODO description)"

• Introduction
o How to read this document
o Structure
• Core Principles
o Provisioning APIs
• API Design
• Consistency Fundamentals
• References and Hypertext
• API Security
• API implementation and development

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 5
API and Services at Hub IT – API Design Concept

2.2 Structure
This concept ist listing various aspects of API design and API development. Core Principles
provides some overarching and general concepts which MUST be followed. API Design
describes hints one SHOULD consider while defining and creating APIs. In Consistency
Fundamentals we list common behaviours and features of our APIs which in general MUST be
adhered.
API implementation and development provides hints for implementing an API specification.
All detail statements are listed using Heading5 paragraphs.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 6
API and Services at Hub IT – API Design Concept

3 Core Principles
The core principles describe some basic features for API design at Lufthansa. They form the
main API Design and API Thinking basis together with some basic constraints.

3.1 API First


Creating and Thinking APIs is a core concept for Lufthansa. Every project or product
development MUST treat API Design as a first class citizen within their development process
It is RECOMMENDED to utilise contract-first API Design and creating a API Specification before
actual API/Service implementation. This allows early separation of concerns and enables
involved parties to base their work on the contracted specification.
The API Specification MUST be the main document created for an API and an API
implementation MUST comply to a specific version of it.
An API is a collection of services/resources which share a specific business boundary,
e.g. a domain boundary.

3.2 Language
Any API content as well as documentation MUST use U.S. English language.
OpenAPI Specification
It is important to differentiate between an API description and an API implementation. The API
description forms the contract everybody can rely on and use as reference within their
respective tasks. An API description is valid for a set of resources/services grouped together.
Therefore an API MUST be described using the OpenAPI/Swagger specification. Version 2.0
MUST be used.
An API description MUST be put under version control.
An API description SHOULD be self contained an contain all information required to use the
API.
An API description SHOULD include examples which demonstrate how an API is used.
An API description MAY contain hints toward the business process and even note some
behavioural aspects. While this is often an implementation detail, in real life hints towards an
API boundaries, its behaviour and its quality attributes are useful information for the API
consumer.
Explanation of OpenAPI/Swagger format and information on how to create a API specification
document are available within document: API Spec - Swagger v2.0API Spec

3.3 Versioning
Versioning of API assets is REQUIRED. It allows all parties to understand how an API can be
used and how their relation to each other is.
There are at least three assets types which need to be versioned:
1. API Specification - the API Specification is the OpenAPI/Swagger file itself.
The API description in OpenAPI MUST use the title property. The title MUST be unique.
The API description in OpenAPI MUST use the version property with version parts:
major.minor.patch

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 7
API and Services at Hub IT – API Design Concept

o major version MUST remain stable for compatible changes. If an API's behaviour
changes, while the interface remains stable, the major version SHOULD be
updated or a new API resource name SHOULD be chosen.
o minor version MUST be updated for changes which are backward compatible.
o patch version MUST be updated if the specification is amended or extended, e.g
with examples or additional information. It MUST NOT be updated while the API
Implementation is patched.

The API description version SHOULD be updated accordingly to API design change.
2. API Implementation - the implementation referes to the code and configuration assetts,
which are in most cases version controled by a VCS.
An API Implementation supports an API Specification (aka Contract) either completely or
partly. A set of micro services might serve specific paths of an holistic API.
Provision of an API to the consumer is always based on the API specification and mediated
using middle-tier layers or service lookup strategies.
The API Implementation SHOULD use versioning parts: major.minor.patch.
o major version SHOULD remain stable for compatible changes
o minor version SHOULD be updated for changes which are backward compatible.
o patch version SHOULD be updated if the implementation is updated/patched, most
likely due to a bug fix.

3. API Route Configuration - this is implementation specific binding used within API Gateways
to connect an API published endpoint to and API implementation
APIs are provisioned on API Gateways. The configuration/binding within the API Gateway
wich binds the API contract to an API Implementation MUST be versioned.
Extenting APIs
When you are making a change to your API you SHOULD follow these rules for extending:
1. You SHOULD NOT take anything away
2. You SHOULD NOT change processing rules
3. You SHOULD NOT make optional things required
4. Anything you add SHOULD be optional
These set focus on retaining backward-compatibility.
Because of these rules the API surface should be kept at the minimum (once you introduce
something you cannot take it away). Likewise, the client must be liberal in what it accepts (e.g.,
ignoring anything it doesn’t understand — Postel’s law).

3.4 Provisioning APIs

3.4.1 API Gateway provisioning


All APIs MUST be provisioned on one of the internal API Gateways.
Internet facing APIs MUST be provisioned on the LHG Open API Gateway.
All REST APIs MUST be secured with OAuth 2.0 bearer access tokens.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 8
API and Services at Hub IT – API Design Concept

4 API Design

While designing new APIs, consider what value the API provides to the consumer. The API is a
managed product and the API provider needs to understand how this product will be used in
which context.

4.1 Design Outside-in


So API Design MUST be done with Outside-In thinking. Focus on the developer and the
prospective usage scenarios instead of features of your system implementation.

4.2 Follow REST semantics


Every API SHALL deal with resources, do not use any verbs.
Resources in URLs MUST be plural to support collection semantics. Use HTTP request
methods for each operation.
Whenever we require a non-resource type service (if not avoidable), you MUST use POST
requests and a verb at the end of the URI-PATH: POST /dutyplan/print?pages=1-5
Support these methods that make sense for a particular resource. If supported - their meaning
MUST be conform to the definition below.
Method Operation Idempotent* safe* CURD Entire Specific Item
Collection(e.g. (e.g.
HTTP
/customers) /customers/{id})
Verb

GET Retrieve an Read 200 (OK), list 200 (OK),


object. of customers. single
Use customer. 404
pagination, (Not Found), if
sorting and ID not found or
filtering to invalid.
navigate big
lists.

POST Store/Create an Create 201 (Created), 404 (Not


object. 'Location' Found), 409
header with (Conflict) if
link to resource
/customers/{id} already exists..
containing new
ID.

PUT Update/Replace Update/Replace 405 (Method 200 (OK) or


an object. Not Allowed), 204 (No
unless you Content). 404
want to (Not Found), if
update/replace ID not found or
every resource invalid.
in the entire
collection.

DELETE Delete an Delete 405 (Method 200 (OK). 404


object. Not Allowed), (Not Found), if
unless you ID not found or

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 9
API and Services at Hub IT – API Design Concept

Method Operation Idempotent* safe* CURD Entire Specific Item


Collection(e.g. (e.g.
HTTP
/customers) /customers/{id})
Verb

want to delete invalid.


the whole
collection—not
often desirable.

PATCH Update/Modify Update/Modify 405 (Method 200 (OK) or


(Incrementally Not Allowed), 204 (No
update) an unless you Content). 404
object. want to modify (Not Found), if
the collection ID not found or
itself. invalid.

HEAD Retrieve Read 200 (OK), list 200 (OK),


metadata of an of customers. single
object. Use customer. 404
pagination, (Not Found), if
sorting and ID not found or
filtering to invalid.
navigate big
lists.

OPTIONS Retrieve Read 200 (OK), list 200 (OK),


information of customers. single
about a request. Use customer. 404
pagination, (Not Found), if
sorting and ID not found or
filtering to invalid.
navigate big
lists.
(*Idempotent = make that same call repeatedly while producing the same result)
(*Safe methods are HTTP methods that do not modify resources. Safe methods are methods
that can be cached, prefetched without any repercussions to the resource.)

API Design MUST respect proper statehandling. REST requires statelessness (statelessness
constraint) when it comes to any server session state. In REST all state is self-contained and a
reference rather than depending on an external frame of reference. State is controlled by the
client and not inflected by any other means. This allows both scalability and channel
transparency, as state and state references is serializable.

4.3 PATCH and PUT request methods


An API SHOULD support PUT to replace the complete data of the resource with the client
provided value. If the client does not provide a value, it MUST be deleted (nulled or removed
depending on the implementation) on the server side. Read-only values MUST be ignored.
If not all data is known to the client or only a partial update is supported, PATCH SHOULD be
used.
Any derivations of those guidelines MUST be noted in the API Specification.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 10
API and Services at Hub IT – API Design Concept

4.3.1 PUT & PATCH Examples :


Code Block 1 PUT Example

The example below shows how PUT affects the data


Example 1 :
PUT /article/1234 HTTP/1.1 //PUT Method creates new article "red-
stapler" for the known identifier : 1234.
<article>
<title>red-stapler</title>
<price currency="eur">9.50</price>
</article>

Response :
HTTP/1.1 201 Created // 201 Created.
Location: /article/1234

Example 2 : //replace new article as "blue-stapler"


PUT /article/1234 HTTP/1.1 //PUT Method replaces new article "blue-
stapler" using same identifier : 1234.
<article>
<title>blue-stapler</title>
<price currency="eur">10.50</price>
</article>

Response :
HTTP/1.1 200 OK // 200 OK. (replaced red-stapler to blue-
stapler ( id remains same).
Location: /article/1234

Example 3 : //create new article as "green-stapler"


//example is perfectly valid if your API provides this functionality.
PUT /article/green-stapler HTTP/1.1 //PUT Method creates new
article "green-stapler".
<article>
<title>green-stapler</title>
<price currency="eur">11.50</price>
</article>

Response :
HTTP/1.1 201 Created //201 Created.
Location: /article/green-stapler

Code Block 2 PATCH Example

The example below shows how PATCH affects the data


Example 1 :

PATCH /article/green-stapler HTTP/1.1 //PATCH Method to update


partial resource on existing record.
<article>
<price currency="eur">15.95</price> //price update for the green-
stapler
</article>

Response :
HTTP/1.1 200 OK
Location: /article/green-stapler

or
PATCH /article/4321 HTTP/1.1 //PATCH Method to update partial
resource on existing record.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 11
API and Services at Hub IT – API Design Concept

<article>
<price currency="eur">10.95</price> //price update for the green-
stapler or identifier 4321
</article>

Response :
HTTP/1.1 200 OK
Location: /article/4321

4.4 Status Codes


An API MUST use a standard HTTP status codes to convey the result of a service call.
Following convention SHOULD be used:
Codes 2xx for successful operation. Make use of 201 (created - for resource creation) and
202 (accepted - e.g. for batch processing)
Codes 300 for multiple choices selection, if the request is ambigous.
Codes 4xx for presumable client errors. Make use of 404 (not found) to signal conditions the
client can influence by changing the values for the call. The API Gateway will use 401, 403 and
405 to communicate access errors.
Codes 5xx for server related errors. Most of the time the client cannot influence this type or
condition beyond retrying. The API Gateway may use 504 (Gateway Timeout) or 503 (Service
Unavailable), so an API server might use 500 with respective error information to transport its
error state.

4.5 Content-Type
APIs SHOULD support application/json and MAY support application/xml

4.6 Data Types


Handling and selection of data types SHOULD follow these rules:
1. Use Internet Standards. E.g. for date/time types stick to the ISO-8601 norm (e.g. 2017-01-
16T05:15:19Z).
2. For industry - airline specific - items, use common data formats such as 3-letter codes valid
in airline industry, e.g. IATA Industry Data Model, aligned with NDC or OTA or other well
know models
3. Only if needed, use LHGroup specific type naming

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 12
API and Services at Hub IT – API Design Concept

4.7 Data Type Extensibility


While defining types you SHOULD prefer deep nesting over simple types. It's always easier to
add a field within a structure than to exchange a primitive type in favor of a structure.
Code Block 3 Old Type

FlightNumber: {
Airline: "LH",
Number: "123"
}

Code Block 4 New Type

FlightNumber: {
Airline: "LH",
Number: "123",
Suffix = "X"
}

4.8 Minimal APIs


Every API design MUST aim for a minimal API surface without sacrificing on product
requirements.
API design SHOULD NOT include unnecessary resources, relations, actions or data.
API design SHOULD NOT add functionality until deemed necessary (YAGNI principle).

4.9 Handling Asynchronous or Long Running Tasks - Process


Tracking
If some process is defined in an asynchronous way or spans a long time, you SHOULD create a
process tracker resource.
A process tracker resource is created with a POST request.
The API returns a process specific ID and upfollowing GET requests are used to poll for
progress update.
Example
Code Block 5 Create Process Tracker (transfer)

curl -X POST \
https://api-test.lufthansa.com/v2/orders/transfer \
-H 'accept: application/json' \
-H 'authorization: Bearer xxx' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{
"FromFlights" : {
"FromFlight" : [ {
"Arrival" : {
"AirportCode" : "DUS"
},

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 13
API and Services at Hub IT – API Design Concept

"Departure" : {
"AirportCode" : "FRA",
"Date" : "2017-07-05"
},
"MarketingCarrier" : {
"AirlineID" : "LH",
"FlightNumber" : "4551"
},
"CabinType" : "C"
} ]
},
"ToFlights" : {
"ToFlight" : [ {
"Arrival" : {
"AirportCode" : "DUS"
},
"Departure" : {
"AirportCode" : "FRA",
"Date" : "2017-07-05"
},
"MarketingCarrier" : {
"AirlineID" : "LH",
"FlightNumber" : "4817"
},
"CabinType" : "C"
} ]
},
"FulfilmentObjectKey" : [ "FUFI_COP_SUCCESS_TEST71_1" ],
"OrderID" : "TEST71",
"Channel" : "BOT"
}'

Code Block 6 Result of POST (transfer)

{
"ObjectKey": "LH4551-FRA-20170705-FUFI_COP_SUCCESS_TEST71_1",
"FromFlights": {
"FromFlight": [
{
"Arrival": {
"AirportCode": "DUS"
},
"Departure": {
"AirportCode": "FRA",
"Date": "2017-07-05"
},
"MarketingCarrier": {
"AirlineID": "LH",
"FlightNumber": "4551"
},
"CabinType": "C"
}
]
},
"ToFlights": {
"ToFlight": [
{
"Arrival": {
"AirportCode": "DUS"
},
"Departure": {
"AirportCode": "FRA",

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 14
API and Services at Hub IT – API Design Concept

"Date": "2017-07-05"
},
"MarketingCarrier": {
"AirlineID": "LH",
"FlightNumber": "4817"
},
"CabinType": "C"
}
]
},
"FulfilmentObjectKey": [
"FUFI_COP_SUCCESS_TEST71_1"
],
"TransferStatus": "INITIALIZED",
"OrderID": "TEST71",
"Channel": "BOT"
}

Code Block 7 Request Current Status (transfer)

curl -X GET \
https://api-test.lufthansa.com/v2/orders/transfer/LH4551-FRA-20170705-
FUFI_COP_SUCCESS_TEST71_1 \
-H 'accept: application/json' \
-H 'authorization: Bearer xxx' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \

{
"ObjectKey": "LH4551-FRA-20170705-FUFI_COP_SUCCESS_TEST71_1",
"TransferStatus": "SUCCEEDED",
"OrderID": "TEST71"
}

4.10 Service and API Granularity


An API SHOULD form granular and re-useable resources and services. A useful method to
determine the right service granularity is to identify the key entities that the service impacts and
to model their life cycles. There is typically one API operation for each entity life cycle state
transition. Thinking early about logical bounded contexts in your systems can help define
some of these boundaries as well.
Designing an API with an optimal granularity is not straightforward. It is often cultural and is the
result of past API design experiences. In doubt, try to avoid exchanges becoming too big or too
specific.
Pragmatically, it is RECOMMENDED:
• Grouping only resources that are almost always accessed together
• Not embedding collections having many components. For example, a list of current jobs is
limited (it’s difficult to have more than 2 or 3 jobs at the same time) but a list of past work
experiences can be much longer.
• Having at most 2 levels of nested objects (e.g. /v1/users/addresses/countries)
• Have a minimal API surface
• Verify your design against core use cases

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 15
API and Services at Hub IT – API Design Concept

Consider JSON API - includes and JSON API - sparse field sets in your API to see if the
approaches are suitable.
(sources: API Design Guide; How to design a REST API)

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 16
API and Services at Hub IT – API Design Concept

5 Consistency Fundamentals

5.1 URL Structure and Versioning


An API MUST be versioned on URL level. Put the version of your API into the URL ('v' followed
by a single number).
An API SHOULD use a domain references as path element.
An API SHOULD use resources/objects and not verbs
An API MUST use plural names of resources.
An API SHOULD use PascalCase for JSON Data Objects
Code Block 8 URL Structure

/v[0-9]+/domain/resourcePlural?filter=value
/v[0-9]+/domain/resourcePlural/{id}

5.2 Handling URL Length and lengthy Query Parameters


While RFC 7230 does not limit the length of the URL, in real life both sides, clients and servers,
may limit it though.
The server MUST respond with Status Code 414 (URI Too Long) if it cannot handle it.
Services that can generate URLs longer than 2,083 characters MUST make accommodations
for the clients they wish to support.
If lengthy query parameters are required, the API MUST use HTTP POST method instead of
GET. The parameters are posted with Content-Type: application/x-www-form-
urlencoded.

5.3 Reserved resource ids naming in URL path


Following reserved words SHOULD be used to retrieve elements from a collection: First, Last
Use /first to get the 1st element
Code Block 9 /first

GET /orders/first
200 OK
{"id":"1234", "state":"paid"}

Use /last to retrieve the latest resource of a collection


Code Block 10 /last

GET /orders/last
200 OK

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 17
API and Services at Hub IT – API Design Concept

{"id":"5678", "state":"running"}

Following reserved word SHOULD be used to retrieve number of items within a collection:
Count
Use /count to get the current size of a collection
Code Block 11 /count

GET /orders/count
200 OK
{"2"}

5.4 Time and Date format


When using time and date, default MUST be UTC times formatted in ISO8601. This is valid both
for input and output data. If other time formats are required, this MUST explicitly noted. Example
for ISO8601
"FinishedAt": "2012-01-01T12:00:00Z"

5.5 Request Headers


An API SHOULD support following Request Headers
Header Description

Authorization Credential information. This item is required and checked at least on API
Gateway Level.

Accept Valid accept header values are


application/json;
application/xml;
To support canary release versioning, a consumer might specify the minimum
version of the api contract (API Specification)
apiversion=1.1

Content-Type Valid content type header values are


application/json;
application/xml;

If-None- Provide the ETag from a previous request and expect 304 Not Modified
Match

ApplicationID A consumer application identifier. Given to caller

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 18
API and Services at Hub IT – API Design Concept

Header Description

CallerID A consumer subsystem identifier. Created by caller

CallID A (unique) message ID. Created by caller or gateway

CustomerID A multi tenant identifier. Given to caller

5.6 Response Headers


An API SHOULD support following Response Headers.
Header Description

Date The date and time that the message was sent

Content-Type

Content-Encoding

Preference-Applied

ETag Include an ETag Header on cachable requests to mark the resource version

5.7 Error Model


The error response MUST be a single JSON object as specified below.
When populating the error model for your API, consider that on public API access conveying too
much internal information about the implementation may open attack vectors. This is especially
true for stack traces. So reduce the information in the error model to allow consumers to
process the error and have enough information to allow for troubleshooting.

5.7.1 processing errors


Code Block 12 error model

{
"requestIdentifier" → xsd:string,
"serviceHost" → xsd:string,
"processingErrors" → [
{
"processingError" → {
"retryIndicator" → xsd:boolean
"type" → xsd:string
"code" → xsd:integer
"description" → xsd:string
"infoUrl" → xsd:anyURI
"innerError" → {
"type" → xsd:string
"code" → xsd:integer
"description" → xsd:string
"innerError" → {
... optional inner errors ...
}
}
}
},
{

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 19
API and Services at Hub IT – API Design Concept

... next processing error ...


}
]
}

Field Description Required Schema

requestIdentifier Request Identifier to find request in log xsd:string


file.

serviceHost Host where error was created and xsd:string


logged.

processingErrors An array of processing errors. Array

Exactly
one

processingErrors[] → A processing error object. Object


processingError
At least
one

processingErrors[] → A hint for the client denoting if a retry is xsd:boolean


processingError[] → suggested by the service.
retryIndicator
Optional

processingErrors[] → An internal type of the error (like an xsd:string


processingError[] → type exception class specific to an underlying
programming language).
Optional

processingErrors[] → An application-specific error code, xsd:integer


processingError[] → code required for incident management.
Required

processingErrors[] → Human-readable description of the error, xsd:string


processingError[] → possibly to be shown to the user.
description
Optional

processingErrors[] → URI of a resource containing help on the xsd:anyURI


processingError[] → infoUrl error.
Optional

processingErrors[] → Nested error for debug purposes. Object


processingError[] →
Not recommended in production
innerError
systems. Optional

processingErrors[] → As in the parent object: an internal type xsd:string


processingError[] → of the error (like an exception class
innerError → type specific to an underlying programming
language). Optional

processingErrors[] → As in the parent object: an application- xsd:integer


processingError[] → specific error code, required for incident

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 20
API and Services at Hub IT – API Design Concept

Field Description Required Schema

innerError → code management. Required

processingErrors[] → As in the parent object: human-readable xsd:string


processingError[] → description of the error, possibly to be
innerError → description shown to the user.
Optional

processingErrors[] → As in the parent object: nested error for Object


processingError[] → debug purposes.
innerError → innerError
Not recommended in production Optional
systems.
Example

{
"requestIdentifier" : "123456",
"serviceHost" : "lvm-inge-01ct",
"processingErrors": [
{
"processingError": {
"retryIndicator": false,
"type": "InputValidation",
"code": 3200,
"description": "Backend response not valid XML (This happens for
invalid cities or invalid date/time range).",
"infoUrl":
"http://api.lufthansa.com/errorcodes/{processingError.Code}"
"innerError": {
"code": 120,
"innerError": {
"code": 44567,
"description": "Exception in thread \"main\"
java.lang.NullPointerException at
com.example.myproject.Book.getTitle(Book.java:16)"
}
}
}
}
]
}

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 21
API and Services at Hub IT – API Design Concept

6 References and Hypertext


The API guidelines do not prescribe a specific specification for linking resource and describing
affordances.
There are many specification / guidelines on hypertext usage. Currently this API Concept does
not enforce a specific convention (see HAL and JSON API).

6.1 General Relations


JSON replies MAY include a Meta section to list and reference related resources to support
other ways of representing a resource as well as listing business capabilities and affordances. If
the URL is generic and used as a template use curly brackets to denote the template items.
While providing links, the Relation description SHOULD indicate what business capability is
reachable with the URL.

"Meta": {
"Link": [
"Href":
"https://api.lufthansa.com/v1/references/airports/{cityCode}",
"Rel": "related"
}]
}

6.2 Paging Relations


For Paging you MUST consider using offset and limit query parameters. To indicate the
capability and limits of a pageable resource insert link objects with prev, next and first and last
relation. If using the Paging relations and cannot support all links, omit the respective links from
the list.
When the generation of the output is too large, the service MAY use 403 (Forbidden) status
reply to indicate that the request cannot be fulfilled.

"Meta": {
"Link": [{
"Href": "https:/references/airports/?offset=0&limit=20",
"Rel": "self"
}, {
"Href": "https:/references/airports/?offset=20&limit=20",
"Rel": "next"
}, {
"Href": "https:/references/airports/?offset=340&limit=20",
"Rel": "last"
}]
}

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 22
API and Services at Hub IT – API Design Concept

6.3 Filtering
At the end of the resource path the URL MAY include a query string for specification of filters
and options. This element of the standard URL structure is especially useful for providing
search parameters as well as operation options. If required, the elements MUST be created as
shown in the example: Acombination of simple filters applied for the “orders” resource could be
provided as follows:

orders?customerid={customerId}&type={type}&status={status}

This series of filters could be used to get all orders for a specified customer of a given type and
status.

This same format can be used to specify options for the resource operation, including both the
tag and the value for each option. For example, adding a setting for the “sortby” option to the
above URL:

orders?customerid={customerId}&type={type}&status={status}&sortby=date

This would indicate that the response should include all the orders fitting the filters, and that it
should also use the “date” for the “sortby” option. Some options might be commonly available,
whereas other options might be unique to a given resource and operation.

Whether for filters or options, the tags must be recognized by the web service, and the value
must be in an appropriate format. The available tags for filters and options, as well as the
expected formats for the values provided MUST be defined within the API Specifications.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 23
API and Services at Hub IT – API Design Concept

7 API Security
(#TODO Security is an open Topic w. GI/X)

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 24
API and Services at Hub IT – API Design Concept

8 API implementation and development


This section contains conceptual hints and recommendations for API implementation

8.1 Use Appropriate Status Codes


An API Implementation MUST use the appropriate HTTP status codes to inform the consumer
about the request result.
Status Codes MUST be described in Open API document.

8.2 Robust Implementation


Every API implementation and API consumer MUST follow Postel's law:
Be conservative in what you send, be liberal in what you accept.
For more detail see 8-steps-to-keep-your-api-sane
This goes together with the concept of graceful degradation. An API Implementation MAY
support partial processing or a level of stale data to support the overall business process. If the
API offers graceful degradation, it SHOULD be documented in the API specification (even
though this is an implementation detail)

8.3 Event Driven Design


To support asynchronous processing and prevent a tight (operational) coupling, consider your
API Implementation to support High Availability by offering queuing mechanisms.
On consumption of APIs which are vital for your process, consider features such as
intermediate store and retry.
An API Interface MUST still be HTTPs.

8.4 Guaranteeing “exactly once” semantics


An API MAY use idempotency keys to handle service retry scenarios on mutating endpoints
(stripe.com - idempotency).
When performing a request, a client generates a unique ID to identify just that operation and
sends it up to the server along with the normal payload. The server receives the ID and
correlates it with the state of the request on its end. If the client notices a failure, it retries the
request with the same ID, and from there it’s up to the server to figure out what to do with it.
Clients MAY pass a unique value in with the Idempotency-Key header, which allows a client to
guarantee the safety of distributed operations:
Code Block 13 Idempotency-Key Header

curl https://api.stripe.com/v1/charges \
-u sk_test_BQokikJOvBiI2HlWgH4olfQ2: \
-H "Idempotency-Key: AGJ6FJMkGQIpHUTX" \
-d amount=2000 \
-d currency=usd \
-d description="Charge for Brandur" \
-d customer=cus_A8Z5MHwQS7jUmZ

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 25
API and Services at Hub IT – API Design Concept

If the above Stripe request fails due to a network connection error, you can safely retry it with
the same idempotency key, and the customer is charged only once.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 26
API and Services at Hub IT – API Design Concept

9 API Gateway usage - OpenAPI and LHMDW


Approval state: pending

9.1 Summary
The following best practices describe how to implement the "API Design Concept” for the
Aspect "Provisioning of APIs". It describes technically which setup is implemented and can be
used to provision APIs via the LH OpenAPI and the LH MDW (ZAMBAS R6)
This document provides basic guidance, not in detail product setup and requires to refer to the
operational teams for OpenAPI and LHMDW for support.

9.2 Introduction

9.2.1 Classification of this document


According to the LH Group architecture framework, this document is classified as best practices
and applies to all new projects and products developed within the Lufthansa Group.

Policy

Target Architectures, Concepts & Rules

Guidelines, Patterns & Best Practices

9.3 Scope
The practices herein aim at providing support on provisioning APIs on API Gateway solutions to
make them available for consumption by API consumers.

9.4 API Gateways

9.4.1 LH Open API Gateway


The LH Open API Gateway is setup as a SaaS solution in AWS provided by Tibco. The product
used is Mashery API Management. This is deployed together with a developer portal at
http://developer.lufthansa.com
The LH Open API Gateway defines APIs and API routes. API endpoints can be configured for
LH Internal services accessed via a DMZ hosted by Amadeus in Erding. Calls via this setup will
always be routed via LH MDW for sake of control and security enforcement. Alternatively for
other Group parties, API endpoints on any other DMZ or public facing IP can be setup.
The LH Open API Gateway allows for some level of decentral administration by supporting
Group administrator definitions.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 27
API and Services at Hub IT – API Design Concept

9.4.2 LH MDW Internal Gateway - Zambas R6


LH MDW offers REST (and SOAP) Gateway capabilities for internal routed services. LH MDW
is operated by Amadeus in Erding.

9.5 API Management


An API is taken under management by following the Core Principles of the API Design Concept
and making the API documentation accessible.
To take an API under management, you MUST document it within the API Hub docspace.
To make the API available via public access points, you SHOULD document it within the LHG
Open API Developer Portal.
All API Management solutions care for following aspect of API Access: Access Control, Security
and Rate Limiting/Throttling.

9.5.1 Rate Limiting


An API consumer will get assigned a Rate Limit for making calls to a specific API for even
resource/method.
The rate limitation may also be imposed on a specific customer for whom the API is accessed
by some API client.

9.5.2 Throttling
An API provider SHOULD specify limitation for concurrent API access which will be used to
throttle the load on the server.

9.5.3 Security (#TODO Security is an open Topic w. GI/X)


All calls MUST use HTTPs TLS1.2 protocol.
For mobile client access, security guidelines are available, especially on OAuth and
OpenIDConnect flows.
An API consumer MUST check with the API Management solution, what security features need
to be enabled and can be supported by the gateway.
Security for an API is twofold:
1. Access scope control is protecting access to an API endpoint from a specific application
(client) by a specific user. This is provided by the API Gateway solution
2. Data scope control is govern access to specific data provided by an API, it is a fine grained
(functional) control and MUST be provided by the API implementation.

9.5.3.1 Access scope control


An API consumer MUST register with the API management solutions and setup the respective
Authorization mechanism.
Access information is conveyed by the Authorization HTTP Header field.

Access control to service endpoints MUST be configured either


• On basis of a "generic plan". A generic plan is a preconfigured set of APIs/Endpoints which
can be assiged to a API consumer. It also can define limits/throttles for each endpoint.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 28
API and Services at Hub IT – API Design Concept

• On basis of a "consumer specific plan". A consumer specific plan is a special configured set
of APIs/Endpoints which is exclusivly assiged to one API consumer. It also can define
limits/throttles for each endpoint.

9.5.3.1.1 OAuth based security - Access Scope for accessing endpoints


1. client credential grant flow for api consumer (no end-user) authorization. Access to the API
is controlled by a bundle of endpoints (also named"packages" and "plans"), but not bound
to OAuth-scopes.
2. authorization code grant flow for end user authorization. Access to the end-user resource is
controlled by OAuth-scopes injected from bearer token validation or transported as JWT
Token.

9.5.3.1.2 End-User Consent - Data Scope


(#TODO Needs clarification with Karthik to use scopes based on URI instead of example
below.)
API resources where end-user consent is required SHALL define access rights, called scopes.
Scopes are defined by name and description per API specification and SHOULD be
documented in API specification.
The naming convention for scopes is URI-based (see RFC 3986 Uniform Resource Identifier
(URI): Generic Syntax). In a regular case the resource provider is responsible for determining
user's access rights. In order to enable the OAuth2 server to identify the right resource provider
approving the access to a specific scope, the host part of the scope will identify the resource
provider. The path path of the scope will carry additional information interpreted by a particular
resource provider.
Example:
https://obelisk.dlh.de/passengerList/read
Would be interpreted as:
Scope's Part Meaning

https No real meaning.

obelisk.dlh.de The resource proivider of a virtual name "obelisk.dlh.de" will be asked for
approval of the access rights.
The real DNS-name or IP address of the "obelisk.dlh.de" resource provider
differs from the scope's name in a regular case.

passengerList/read Forwarded 1:1 to the resource provider in the scope authorization request.
Of internal meaning to the "obelisk.dlh.de" service provider only.

9.5.4 Open API Gateway OAuth Scope and User Context support
Open API Gateway setup support OAuth with User Context and scope with OAuth Token
Providers for
• LH Crew Employees
• LH ID Customers
Open API Gateway resolves the access Token provided by API Consumer and forwards it as
header fields to the subsequent API Provider
Header field Content

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 29
API and Services at Hub IT – API Design Concept

Header field Content

X-Mashery- Header set by Mashery API Gateway resolving the bearer token to the stored
Oauth-Scope scope from OAuth2. If used, this scope header MUST be checked for valid
access roles within API implementation

X-Mashery- Header set by Mashery API Gateway resolving the bearer token to the stored
Userscope user-context value from OAuth2. This user-context MAY be used within API
implementation for logging or user information purposes

(#TODO JWT Token Header to be implemented, today OpenAPI GW forwards data as extra
header fields.)

9.6 Logging and Troubleshooting


API headers MUST include information which allows middle tiers and service providers to log
and troubleshoot API calls.
Header field Content

ApplicationID A consumer application identifier. The Authorisation bearer token MAY contain
this information implicitly and the API Gateway will insert the field before calling
the downstream system

CallerID A consumer subsystem identifier. The Authorisation bearer token MAY contain
this information implicitly and the API Gateway might insert the field before calling
the downstream system

CallID A (unique) message ID. The API Gateway might insert the field before calling the
downstream system

CustomerID A multi tenant identifier. The Authorisation bearer token MAY contain this
information implicitly and he API Gateway might insert the field before calling the
downstream system.

9.7 Caching

9.7.1 Open API Gateway Caching capabilities


If used, to control caches you MUST setup cache options within the API Gateway configuration
to define which elements of the call URI and header parameters are used on cache control.

9.7.1.1 Global Caching


The first level of caching is Global Caching. A global TTL is set for all calls in an entire API. A
hash is created based on the URL plus paramters (API Key is removed from the cached call).
Calls with a Cache-Hit within the designated TTL are returned from cache, bypassing the
application server. If a call is a Cache-Miss, the response is stored in cache and TTL set.

9.7.1.2 HTTP Cache-Control Headers (Mashery)


An API consumer MAY use the cache-control header no-store or max-age to control cache
reply.
An API provider MAY use the cache-control header max-age to control cache reply. Alternativly
the Expires header is respected.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 30
API and Services at Hub IT – API Design Concept

10 How to create Swagger v2.0/API Spec


This document will help you to create swagger v2.0 API specification.
Most of the guidelines listed have been referred from existing resources, such as the Swagger
Specification from Swagger.io.
You may download the swagger json / yaml file & copy to swagger editor Swagger Editor to
view the API representation/documentation which covers the security definitions used by
Lufthansa OpenAPI (OAuth 2.0), API Definition includes frequently used Methods (GET, POST,
PUT, DELETE), API Model (schemas, description, examples).
Swagger JSON : Swagger-v2.0.json
Swagger YAML : Swagger-v2.0.yaml
The following are the steps to create swagger 2.0 API Model to include all necessary artifacts
for hosting your APIs :
• The below sections helps you to define creation of Swagger v2.0 API Spec. the details of
each sections are covered in this page.
o Swagger Template - Swagger v2.0 template provides high level skeleton to create
swagger file in JSON format.
o Metadata (swagger version & Info) - Metadata which specifies the swagger v2.0, LH
Open API currently supports Swagger v2.0. Info - allows user to define the "API
Version", "title of API", description (optional) , license - name & url (optional) of
application.
o Base URL - host (dns name / IP address on API), basePath (common path for all
the resources), schemes (https/http protocol scheme).
o security definitions - defines the security you impose on APIs.
o consumes,produces - this section must be added based on your API Spec based
on your API supports to consumes(your API calls producers) other APIs or
produces (clients can call) the API.
o paths - path construction with both path parameters & query parameters.
o parameter types - different types of parameters like header, query, body(request),
responses & model (request/response models). this section cover the Input Model
(request parameter types).
o Request (Input Model) - In case of POST, PUT & PATCH methods, the request
construction using object payload & primitive types.
o Responses (output Model)- types of response codes & reference to usage of model
(definitions).
o Examples - How to define examples.

10.1 Swagger v2.0 template


Swagger can be written in JSON or YAML. In this guide, we only use JSON examples, but
YAML works equally well. Please refer Swagger UI View after following the below steps
The sample Swagger specification written in JSON looks like:
Code Block 14 Swagger-Template

{
"swagger": "2.0",
"info": {

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 31
API and Services at Hub IT – API Design Concept

"version": "1.0.0", // for ex: "1.0-beta" or "1.1.2" etc.


"title": "LH Public Open API", // Title of the API "LH Public
Flight Status API" or "LH Partner Orders API" or "LH Internal Operations
API" etc.
"description": "LH Public Open API - Users for demonstration",
"license": {
"name": "Lufthansa Group", //swiss airlines or Lufthansa .. etc
"url": "https://developer.lufthansa.com"
}
},
"host": "api.lufthansa.com", // host name where the API hosted for
consumption. (IP & port / dns name).
"basePath": "/v1", // basepath - common path for all the below
resources used for this API. for ex: /v1/orders or /v1/operations or
/v1.1/orders etc.
"schemes": [ // scheme dectates if this API support only https
or http or both.
"https",
"http"
],
"securityDefinitions": {
// this section contains the various security definitions. refer
security section below.
},

"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths" : {
// this section contains corresponding resources, descriptions,
request & response model references, request & response examples. refer
paths section below
},
"definitions" : {
//model of the API request & response schemas.
}
}

10.2 Metadata (Swagger version, Info)


Swagger specification starts with the Swagger version, 2.0 being the latest version. A Swagger
version defines the overall structure of an API specification.
Info section supports other fields for contact information, license and other details as shown in
below example .
Code Block 15 Metadata & Info

{
"swagger": "2.0",
"info": {
"version": "1.0.0", // for ex: "1.0-beta" or "1.1.2" etc.
"title": "LH Public Open API",
"description": "LH Open API - Users",
"termsOfService": "http://developer.lufthansa.com/terms/",
"contact": { //API suppor contact details
"name": "API Support",
"url": "https://developer.lufthansa.com",

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 32
API and Services at Hub IT – API Design Concept

"email": "api.support@dlh.de"
},
"license": {
"name": "LHG",
"url": "https://developer.lufthansa.com/licenses.html"
}
}
}

10.3 Base URL


The base URL for all API calls is defined using schemes, host and basePath:
1. host - host name or dns name or IP /Port number where you host your API.
2. basepath - mange the same base path against all the "paths or resources" this is to avoid
the same representation of resource paths for all resources. for example "v1/api" or
"v1/cargo" or "v1/passanger" etc.
3. schemes - mention to support both http & https
please refer baseurl for more details & examples
Code Block 16 Base URL (Host, basepath,schemes)

{
"swagger": "2.0",
....
"host": "api.lufthansa.com", //host or dns or IP/port
"basePath": "/v1", // common path across all resources : for
example : /v1 or "v1/api" or "v1/cargo" or "v1/passanger" etc . without
forward slash is incorrect for ex: "v2"
"schemes": [ // this section defines API to consume /
produce protocols for ex: https or http or both.
"https",
"http"
],
.....
}

10.4 Security Definitions


Allows the definition of a security scheme that can be used by the operations. Supported
schemes are basic authentication, an API key (either as a header or as a query parameter) and
OAuth2's common flows (implicit, password, application and access code).
Please view the link of security defintions to authorise before using the backend API call.

10.4.1 Fixed Fields


Field Name Type Validity Description

type string Any Required. The type of the security


scheme. Valid values are "basic",
"apiKey" or "oauth2".

description string Any A short description for security scheme.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 33
API and Services at Hub IT – API Design Concept

Field Name Type Validity Description

name string apiKey Required. The name of the header or


query parameter to be used.

in string apiKey Required The location of the API key.


Valid values are "query" or "header".

flow string oauth2 Required. The flow used by the OAuth2


security scheme. Valid values are
"implicit", "password",
"application" or "accessCode".

authorizationUrl string oauth2 ("implicit", Required. The authorization URL to be


"accessCode") used for this flow. This SHOULD be in the
form of a URL.

tokenUrl string oauth2 ("password", Required. The token URL to be used for
"application", this flow. This SHOULD be in the form of
"accessCode") a URL.

scopes Scopes oauth2 Required. The available scopes for the


Object OAuth2 security scheme.
please refer this link for more details on oauth2
Code Block 17 SecurityDefinitions

{
"swagger": "2.0",
....
"securityDefinitions": {
"auth": {
"type": "oauth2",
"scopes": {
"read:LH Open API": "read access"
},
"flow": "accessCode",
"authorizationUrl": "https://api.lufthansa.com/v1/oauth/token",
"tokenUrl": "https://api.lufthansa.com/v1/oauth/token"
}
}
.....
}

10.5 consumes, produces


The consumes and produces sections define the MIME types supported by the API. The root-
level definition can be overridden in individual operations.
MIME types listed in consumes and produces should be compliant with RFC 6838. For
example, you can use standard MIME types such as:
application/json
application/xml
application/x-www-form-urlencoded
multipart/form-data
text/plain; charset=utf-8
text/html
application/pdf
image/png

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 34
API and Services at Hub IT – API Design Concept

as well as vendor-specific MIME types (indicated by vnd.):


application/vnd.mycompany.myapp.v2+json
application/vnd.ms-excel
application/vnd.openstreetmap.data+xml
application/vnd.github-issue.text+json
application/vnd.github.v3.diff
image/vnd.djvu
Please refer link for more details.
Code Block 18 consumes,produces

{
"swagger": "2.0",
....
"consumes": [
"application/json", //define the MIME Types your application
supports for ex: xml, json, pdf, text etc. for both consumes or produces
section.
"application/xml"
],
"produces": [
"application/json",
"application/xml"
],
.....
}

10.6 Paths
paths are endpoints (resources) that your API exposes, such as /users or
/reports/summary, and operations are the HTTP methods used to manipulate these paths,
such as GET, POST or DELETE.
paths:
/ping:
...
/users:
...
/users/{id}:
...
path templats examples :
/users/{id}
/organizations/{orgId}/members/{memberId}
/report.{format}

Query String in Paths : Query string parameters must not be included in paths
GET /users?firstName=value&lastName=value
GET /users?role=value
Incorrect :
paths:
/users?role={role}:
Please refer link for more details on paths. the below section describes & contains most of the
infomration on paths.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 35
API and Services at Hub IT – API Design Concept

Code Block 19 paths (endpoints & methods)

{
"swagger": "2.0",
....
"paths": {
"/flightstatus/{flightnumber}/{date}": { //the path starts here &
support both POST & GET operations.
"get": {
"tags" : ["flightstatus"],
"summary": "Returns a list of flights by flightnumber & date.",
"description": "Optional extended description in Markdown.",
"operationId": "getflightsbyflightnumber"
"produces": "application/json",
"parameters" : [ ] //refer Parameter types section
"responses": {
"200": {
"description": "OK or Success",
"schema": {
"$ref": "#/definitions/schemas" // refer "deinitions"
section for more detials.
},
"examples" : {} //refer example section below for more
details.
}
}
}, //get opeation ends
"POST": {
"tags" : ["create flight infomration"],
"summary": "Returns a list of flights by flightnumber & date.",
"description": "Optional extended description in Markdown.",
"operationId": "getflightsbyflightnumber"
"produces": "application/json",
"parameters" : [ ], //refer below Parameter types section
"request" : {} , //refer below request section. this is valid for
all operations / methods (GET,"PUT","POST", DELETE).
"responses": {
"201": {
"name" : "Successfully created flight inforamtion"
"description": "OK or Success",
"schema": {
"$ref": "#/definitions/schemas" // refer "response
(output model) section" section for more detials.
},
"examples" : {} //response example.
}
}
} //POST opeation ends
}, // path end here.
//antoher new path can be added below
"/ping": {
...
},
"/users": {
...
},
"/users/{id}": {
...
}
}
....
}

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 36
API and Services at Hub IT – API Design Concept

10.7 Parameter Types , Request, Response, Definitions (Input


Model)
Swagger distinguishes between the following parameter types based on the parameter location.
The location is determined by the parameter’s in key, for example, in: query or in: path.
• query parameters, such as /users?firstname=admin
• path parameters, such as /users/{username}
• header parameters, such as X-MyHeader: Value
• body parameters that describe the body of POST, PUT and PATCH requests (see
Describing Request Body)
• form parameters – a variety of body parameters used to describe the payload of requests
with Content-Type of application/x-www-form-urlencoded and
multipart/form-data (the latter is typically used for file uploads)
please refer describing-parameters type for more information on paramter types
The below example cover the below URL ith query, header, body parameter with definitions of
request & resposne :
ex: /users/{username}?emailaddress=xyz@dlh.de&firstname="admin"&lastname="root"
path parameter : {username}
query paramter : emailaddress=xyz@dlh.de&firstname="admin"&lastname="root"
Note : "?" separate the path and query parameters. "&" symbol separates each query paramter.
Code Block 20 parameter types

{
"swagger": "2.0",
...."paths" : {
"/users/{username}" : {
"post" : {
"tags" : [ "create user" ],
"summary" : "create user",
"description" : "create user for given firstname, lastname,
username, emailaddress.",
"operationId" : "create user",
"produces" : [ "application/json", "application/xml" ],
"parameters" : [ {
"name" : "createuser",
"in" : "body", // this parameter "in" : "body" only
applicable for "POST" & "PUT".
"schema" : {
"$ref": "#/definitions/requestschema" //this is reference to
request schema & referred at end of swagger with "definitions" object
},
"examples" : {} //not allowed for POST, PUT & PATCH in swagger
v2.0.
},{
"name" : "username",
"in" : "path", // this paratmer is path parameter
/{username}
"description" : "username (unique)",
"required" : true,
"type" : "string",
"default" : "DK"
}, {
"name" : "emailaddress",
"in" : "query", // this parameter is for query parameter
for ex: /users/{username}?emailaddress=xyz@dlh.de

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 37
API and Services at Hub IT – API Design Concept

"description" : "2 letter ISO 3166-1 language code",


"required" : false,
"type" : "string"
}, {
"name" : "firstname",
"in" : "query", // this parameter is for query parameter for
ex: /users/{username}?emailaddress=xyz@dlh.de&firstname="ananda"
"description" : "Number of records returned per request.
Defaults to 20, maximum is 100 (if a value bigger than 100 is given, 100
will be taken)",
"required" : true,
"type" : "string",
"default" : "Ananda"
}, {
"name" : "lastname",
"in" : "query", // this parameter is for query parameter for
ex:
/users/{username}?emailaddress=xyz@dlh.de&firstname="ananda"&lastname="Red
dy"
"description" : "Number of records skipped. Defaults to 0",
"required" : true,
"type" : "string",
"default" : "Reddy"
}, {
"name" : "Accept",
"in" : "header", // this parameter is header parameter.
"description" : "http header: application/json or
application/xml",
"required" : true,
"type" : "string",
"default" : "application/json"
} ],
"responses" : {
"200" : {
"description" : "Successful Response",
"schema" : {
"$ref": "#/definitions/responseschema"
}
}
}
}
}
},
"definitions" : { //this is definitions section defines more on the
request & resposne objects based on your application.
"requestschema" : {
"type": "object",
"properties": {
"createUserRequest" : {
"type" : "string"
}
}
},
"responseschema" : {
"type": "object",
"properties": {
"createUserResponse" : {
"type" : "string"
}
}
}
}
....

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 38
API and Services at Hub IT – API Design Concept

10.8 Request (Input Model)


The POST, PUT and PATCH requests can have the request body (payload), such as JSON or
XML data. In Swagger terms, the request body is called a body parameter. There can be only
one body parameter, although the operation may have other parameters (path, query, header).
• Object Payload : (in parameters section always mention : "in" : "body") any APIs transmit
data as an object, such as JSON. schema for an object should specify type: object and
properties for that object. (JSON, XML, PDF etc)
• Primitive types :(in parameters section always mention : "in" : "header" / "in" : "formData" /
"in" : "query" / "in" : "path".) you can define the body schema type as a primitive, such as a
string or number.
More information on request body please refer link

Code Block 21 Request

{
"swagger" : "2.0",
...
paths : {

// Options 1 : Object Payload


/users/{username} : {
post : {
...
"parameters" : {
"name" : "createuser",
"in" : "body", // this parameter "in" : "body" only
applicable for "POST","PUT" & "PATCH. this is of type Object Payload
"schema" : {
"$ref": "#/definitions/requestschema" //this is reference
to request schema & referred at "definitions" object
},
"examples" : {} //not allowed for POST, PUT & PATCH in swagger
v2.0.
}
}
}
....

// Options 2 : Primitive Types


"/status":{
"post" : {
"tags" : [ "Status updates" ],
"summary" : "Updates the status message.",
"description" : "status updates.",
"operationId" : "statusupdates",
"consumes" : ["application/x-www-form-urlencoded",
"multipart/form-data" ],
"parameters" : [{
"in" : "formData", // this parameter "in" : "body" only
applicable for "POST","PUT" & "PATCH. this is of type Object Payload.
// example primitive types : header, formData, query,
path.
"name" : "status",
"type": "string"
}],
"responses": {
"200": {
"description": "Success!",
"schema" : {
"$ref": "#/definitions/responseschema"

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 39
API and Services at Hub IT – API Design Concept

}
}
}
}
}
}, //paths will end here.
....
"definitions" : { //this is definitions section defines more on the
request & resposne objects based on your application.
"requestschema" : {
"type": "object",
"properties": {
"createUserRequest" : {
"type" : "string"
}
}
},
"responseschema" : {
"type": "object",
"properties": {
"createUserResponse" : {
"type" : "string"
}
}
}
}

10.9 Responses (Output Model)


An API specification needs to specify the responses for all API operations. Each operation
must have at least one response defined, usually a successful response. A response is defined
by its HTTP status code and the data returned in the response body and/or headers.
More details please refer to link
Code Block 22 Responses

{
"swagger" : "2.0",
...
"/users/{username}" : {
"post" : {
"tags" : [ "create user" ],
"summary" : "create user",
"description" : "create user for given firstname, lastname,
username, emailaddress.",
"operationId" : "create user",
"produces" : [ "application/json", "application/xml" ],
"parameters" : [ {
//request, query, path paramters to define here.
}],
/* the below section is response structure for various status */
"responses" : {
"200" : {
"description" : "Successful Response",
"schema" : {
"$ref": "#/definitions/responseschema" //refer below
definitions block for schema definitions or model.
}

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 40
API and Services at Hub IT – API Design Concept

},
"400": {
"description": "Bad request. User ID must be an integer and
bigger than 0.",
"schema" : {
"$ref": "#/definitions/errorSchema" //refer below
definitions block for schema definitions or model.
}
},
"401": {
"description": "Authorization information is missing or
invalid.",
"schema" : {
"$ref": "#/definitions/errorSchema" //refer below
definitions block for schema definitions or model.
}
},
"404": {
"description": "A user with the specified ID was not found.",
"schema" : {
"$ref": "#/definitions/errorSchema"
}
}
} //end of responses block
}, //end of paths block
/* the below section definitions which defines the Model for request &
responses */
"definitions" : {
"requestschema" : { //request schema with simple string & more
infomration will be discussed in "Input & Output Models" section.
"type": "object",
"properties": {
"createUserRequest" : {
"type" : "string"
}
}
},
"responseschema" : { //response schema with simple string & more
infomration will be discussed in "Input & Output Models" section.
"type": "object",
"properties": {
"createUserResponse" : {
"type" : "string"
}
}
},
"errorSchema" : { //error schema referred for 400, 401, 404 resposne
codes.
"type": "array",
"items": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"ProcessingErrors": {
"type": "object",
"properties": {
"ProcessingError": {
"type": "object",
"properties": {
"@RetryIndicator": {
"type": "string",
"default": "false"
},

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 41
API and Services at Hub IT – API Design Concept

"Type": {
"type": "string",
"default": "InputValidation"
},
"Code": {
"type": "integer",
"default": 2202
},
"Description": {
"type": "string",
"default": "Invalid flight number in flight status
request (formally incorrect). Example: /flightstatus/LH400/2014-12-03."
},
"InfoURL": {
"type": "string",
"default": "not supported yet:
http://api.lufthansa.com/errorcodes/{processingError.Code}"
}
}
}
}
}
}
}
}
}
}
} //end of definitions
}

10.10 Examples (Input & Output Model)


An API specification can include examples for:
• response MIME types,
• schemas (data models),
• individual properties in schemas.
Examples can be used by tools and libraries, for instance, Swagger UI auto-populates request
bodies based on input schema examples, and some API mocking tools use examples to
generate mock responses.
Note: Do not confuse example values with the default values. An example is used to illustrate
what the value is supposed to be like. A default value is something that the server uses if the
value is not provided in the request.

10.11 Schema Examples


The examples key is used to provide a schema example. Examples can be given for individual
properties, objects, arrays and the whole schema. there are two options to provide examples :
1. Examples at Model
2. Examples at responses
More details please refer to link provides information on creation of various types of examples.

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 42
API and Services at Hub IT – API Design Concept

Code Block 23 Examples

{
"swagger" : "2.0",

"responses" : {
"200" : {
"description" : "Successful Response",
"schema" : {
"$ref": "#/definitions/responseschema" //definitions
model will also contains the examples.
},
"examples": { //direclty mentioning the examples at
responses at method level but recommeded to use at definitions
//which helps in reusablity & no need to mention
the exampels for each method.
// swagger editor will not show the root element
while you mention the example at "responses".
// but the actual API response will contain the
root element "createUserResponse" tag.
"createUserResponse": {
"id": 38,
"title": "T-shirt"
}
}
},

... // examples to add at model creation itself


"definitions" : {
"CatalogItem": {
"type" : "object",
"required": ["id", "title"], //madatory elements "id" & "title"
"properties" : {
"id" : {
"type": "integer",
"example": 38, //example at Model values based on the type
of the element.
},
"title": {
"type": "string",
"example": "T-shirt"
}
}
},
"responseschema" : {
"type": "object",
"properties": {
"createUserResponse" : {
"$ref": "#/definitions/CatalogItem" //this is refered from the
"CatalogItem" in line #5 above
}
}
}

Fehler! Verwenden Sie die Registerkarte 'Start', um Heading 1 dem Text zuzuweisen, der hier
angezeigt werden soll. – 43

You might also like