Skip to main content

API Specification

API specifications are crucial. They provide standard rules and guidelines for integrating an API and serve as a single source of truth for software engineers.

In this section, you will learn
  • What is API Specification
  • Why do you need an API specification and,
  • Types of API Specification

What is API Specification?

An API specification is a standardized format that describes the behavior and elements of an API, ensuring clear communication and integration among developers.

The specification describes endpoints, operations on each endpoint, query and path parameters, methods, schemas, version descriptions, and more.

All these elements are compiled into a specification file, which is usually created during the development stage of the API. However, APIs with predefined specifications by governing bodies are exceptions.

API specifications are technical and often lack detailed explanations, requiring technical writers to provide comprehensive descriptions translated into API documentation. While specifications outline API elements, they don't instruct on usage.

info

An API specification is not the same as an API architectural style

Why do you need an API Specification?

An API specification offers clear, standardized guidelines detailing how an API should operate and interact with other software components. It ensures consistent communication by defining expected behavior, data formats, and protocols. This eliminates the need for developers to rely on internal implementation details.

Moving further, a well-defined API specification fosters collaboration among teams. It minimizes misunderstanding and reduces the time spent on API integration.

In addition, an API specification serves as a single source of truth that can be easily shared and modified, simplifying the development process. As a result, integration becomes significantly easier when APIs are clearly defined. Third-party developers can integrate their products seamlessly by referring to the specifications rather than relying on trial and error.

Finally, security is essential in API development. An API specification enables developers to implement essential security measures, such as authentication, rate limiting, and encryption, to protect sensitive data.

Types of API Specification

There are various types of API specifications with different formats

  1. Open API Specification(OAS)
  2. Restful API Modelling Language(RAML)
  3. API Blueprint
  4. GRAPHQL Schema Definition Language(SDL)
  5. Web Application Description Language(WADL)

This section will focus on the first three API specification types.

Open API Specification

OAS, previously known as the Swagger specification, is a format for describing, producing, consuming, and visualizing restful web services. It evolved from the Swagger framework and is now managed by the Open API Initiative(OAI) under the Linux Foundation. It is an open-source collaboration project of the Linux Foundation.

This specification defines the structure and syntax of REST APIs, making it easy for developers to build consistent APIs that adhere to Industry standards. One of the most significant advantages of open APIs is that they are language agnostic. This means that humans and computers can identify and understand service capabilities without requiring additional documentation or access to source code.

An Open API file, sometimes called an Open API document, describes an API, including endpoints, authentication methods, operation parameters, and contact information. It can be written in YAML or JSON. Big organizations like Google, Postman, Oracle, and more use the OAS.

Top-Level Structure of an Open API Specification

Structure of an API Specification

Image Source:Swagger.io

  • openapi: This section specifies the version of the OAS. The OAS has different versions.
tip

You can write your OAS in YAML or JSON. I will use YAML for the example descriptions. One thing you should know about YAML is that it is indentation-sensitive.

openapi: 3.0.0
  • info: This section provides metadata about the API, including title, description, version, contact, license, etc. It gives a general overview of what the API does.
info:
description: |
This is a sample Petstore server. You can find
out more about Swagger at
[http://swagger.io](http://swagger.io) or on
[irc.freenode.net, #swagger](http://swagger.io/irc/).
version: "1.0.0"
title: Swagger Petstore
termsOfService: 'http://swagger.io/terms/'
contact:
email: apiteam@swagger.io
license:
name: Apache 2.0
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
  • servers: This section defines the base URLs for accessing the API. You can add multiple server URLs, such as production and testing environments, as supported by OAS 3.0
    servers:
- url: 'https://petstore.swagger.io/v2'
  • tags: This section contains a collection or group of related operations. Tags can also be added to path operations to add clear descriptions. For example, the pet store API has tags like user, pet, store, and more.
tags:
- name: pet
description: Everything about your Pets
  • paths: This section lists all the API paths/endpoints available and the HTTP methods supported for each path. It contains request and response objects.
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pet
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'default':
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pet
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: integer
format: int64
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
'default':
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
  • components: This section holds reusable objects for parameters, schemas, responses, etc. These components can be referenced in any path item.
components:
securitySchemes:
petstore_auth:
type: oauth2
flows:
implicit:
authorizationUrl: 'http://petstore.swagger.io/oauth/dialog'
scopes:
write:pets: modify pets in your account
read:pets: read your pets
api_key:
type: apiKey
name: api_key
in: header
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
  • Security: This section defines the security mechanisms that can be used across the API and includes information on authentication and authorization. The OAS supports various security mechanisms, such as 0Auth2, API Key, OpenID, HTTP for basic bearer, and other authentication schemes.
security:
- petstore_auth: []
- api_key: []
  • External Docs: This section allows you to reference external documentation by adding links.
externalDocs:
description: Find out more
url: 'http://swagger.io'

Here is the full example code. You can preview it using the Swagger editor.

openapi: 3.0.0
info:
description: |
This is a sample Petstore server. You can find
out more about Swagger at
[http://swagger.io](http://swagger.io) or on
[irc.freenode.net, #swagger](http://swagger.io/irc/).
version: "1.0.0"
title: Swagger Petstore
termsOfService: 'http://swagger.io/terms/'
contact:
email: apiteam@swagger.io
license:
name: Apache 2.0
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
servers:
- description: SwaggerHub API Auto Mocking
url: https://virtserver.swaggerhub.com/JudyPearls/Pet/1.0.0
- url: 'https://petstore.swagger.io/v2'
tags:
- name: pet
description: Everything about your Pets
externalDocs:
description: Find out more
url: 'http://swagger.io'
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pet
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'default':
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pet
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: integer
format: int64
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
'default':
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
securitySchemes:
petstore_auth:
type: oauth2
flows:
implicit:
authorizationUrl: 'http://petstore.swagger.io/oauth/dialog'
scopes:
write:pets: modify pets in your account
read:pets: read your pets
api_key:
type: apiKey
name: api_key
in: header
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
security:
- petstore_auth: []
- api_key: []

Here is how the preview will look like

Swagger editor preview

0AS Tools

  • SwaggerHub: SwaggerHub is a collaborative platform developed by SmartBear that allows teams to design, manage, and publish APIs using the OAS. It offers a premium version of the open-source Swagger tools, providing enhanced features for API documentation.

  • PostMan: This tool allows users to import APIs created with Swagger and other OpenAPI specifications.

  • Swagger Codegen: Swagger Codegen is a tool that generates client libraries, server stubs (generated code), and API documentation from an OpenAPI Specification.

Other tools include: Open API generator, API Dog, and more.

RAML Specification

RAML, which stands for RESTful API Modeling Language, is a specification language designed to describe RESTful APIs in a structured and human-readable format. It utilizes YAML (YAML Ain't Markup Language) as its syntax, making it accessible for developers and non-developers to understand and use.

The language's focus on modeling rather than documenting APIs has set it apart from other specifications like OAS. This distinction has led many organizations to adopt RAML for their API design processes, particularly during the early stages of development.

With the rise in adoption of the OAS, RAML is no longer popular.

Brief History of RAML

RAML was first introduced in 2013. Its goal was to provide a more effective way to design APIs compared to existing standards like Swagger (now OpenAPI). It was developed to facilitate API design rather than document existing APIs.

Moving on, in 2015, the Open API Initiative was established under the Linux Foundation to standardize HTTP API descriptions. While RAML was considered, Swagger became the primary focus of this initiative.

A year later, on May 16, 2016, the latest major release of RAML, version 1.0, was launched. This version introduced several enhancements aimed at improving usability and modularity.

Basic Structure of a RAML Specification

A basic RAML specification starts with a version declaration, followed by metadata about the API, and then the definition of resources and their associated methods. Here’s a breakdown of the specification structure.

  • Version Declaration: In RAML, you must define the version of the document.
#%RAML 1.0   
  • Metadata: This section contains detailed information about the API, such as the title, version, and base URL.
title: e-BookMobile API
baseUri: http://api.e-bookmobile.com/{version}
version: v1
  • Resource Definition: Resources represent the various API endpoints. Each resource is defined with a leading slash and can have nested resources.
 /users:
/authors:
/books:
  • Method: Each resource supports various HTTP methods (GET, POST, PUT, DELETE), which are defined under their respective resources.
 /books:
get:
  • Query Parameter: In RAML, you can define query parameters for a resource or method to filter, sort, or paginate the returned data.
 /books:
get:
queryParameters:
author:
displayName: Author
type: string
description: An author's full name
example: Mary Roach
required: false
publicationYear:
displayName: Pub Year
type: number
description: The year released for the first time in the US
example: 1984
required: false
rating:
displayName: Rating
type: number
description: Average rating (1-5) submitted by users
example: 3.14
required: false
isbn:
displayName: ISBN
type: string
minLength: 10
example: 0321736079
required: false

  • Responses: Responses define the expected outcomes of API calls, including HTTP status codes and response bodies.
 /{bookTitle}:
get:
description: Retrieve a specific book title
responses:
200:
body:
application/json:
example: |
{
"data": {
"id": "SbBGk",
"title": "Stiff: The Curious Lives of Human Cadavers",
"description": null,
"datetime": 1341533193,
"genre": "science",
"author": "Mary Roach",
"link": "http://e-bookmobile.com/books/Stiff"
},
"success": true,
"status": 200
}

Here is the full code example

   #%RAML 1.0
---
title: e-BookMobile API
baseUri: http://api.e-bookmobile.com/{version}
version: v1
/users:
/authors:
/books:
get:
queryParameters:
author:
displayName: Author
type: string
description: An author's full name
example: Mary Roach
required: false
publicationYear:
displayName: Pub Year
type: number
description: The year released for the first time in the US
example: 1984
required: false
rating:
displayName: Rating
type: number
description: Average rating (1-5) submitted by users
example: 3.14
required: false
isbn:
displayName: ISBN
type: string
minLength: 10
example: 0321736079
required: false
/{bookTitle}:
get:
description: Retrieve a specific book title
responses:
200:
body:
application/json:
example: |
{
"data": {
"id": "SbBGk",
"title": "Stiff: The Curious Lives of Human Cadavers",
"description": null,
"datetime": 1341533193,
"genre": "science",
"author": "Mary Roach",
"link": "http://e-bookmobile.com/books/Stiff"
},
"success": true,
"status": 200
}

Preview Documentation with RAML Github Play Ground

Raml Github playground

RAML Tools

  • API Designer: A web-based editor for creating and sharing RAML API specifications. It provides suggestions for elements and highlights errors in the RAML document.

  • RAML TO OAS*: This tool converts RAML API specifications to OpenAPI specifications.

Other tools include RAML parser, raml2html, API Console, and more. Visit the RAML Project page to learn more about RAML tools.

API Blueprint Specification

API Blueprint is a high-level API specification language designed for creating and documenting web APIs. It uses a syntax similar to Markdown, known as MSON (Markdown Syntax for Object Notation), which makes it easy for humans to read and write while still being processable by machines.

API Blueprint is ideal for projects that need clear documentation and rapid prototyping. The file is saved with a .apib extension.

Basic Structure of an API Blueprint Specification

  • Metadata: This section includes general information about the API, such as its title, version, and other basic information.
  FORMAT: 1A
HOST: https://polls.apiblueprint.org/
  • API Name & Overview Section: This section briefly describes the API, including its name and purpose.
    # Poll API
Polls is a simple API allowing consumers to view polls and vote in them.
  • Resource Group Section: These sections group related resources together.
    ## Questions Collection [/questions]
  • Action Sections: Define the actions that can be performed on resources, such as HTTP methods (GET, POST, etc.). Each action section can specify requests, responses, headers, and more.
 ### List All Questions [GET]  
+ Response 200 (application/json)

[
{
"question": "Favourite programming language?",
"published_at": "2015-08-05T08:40:51.620Z",
"choices": [
{
"choice": "Swift",
"votes": 2048
}, {
"choice": "Python",
"votes": 1024
}, {
"choice": "Objective-C",
"votes": 512
}, {
"choice": "Ruby",
"votes": 256
}
]
}
]
### Create a New Question [POST]

You may create your own question using this action. It takes a JSON
object containing a question and a collection of answers in the
form of choices.

+ Request (application/json)

{
"question": "Favourite programming language?",
"choices": [
"Swift",
"Python",
"Objective-C",
"Ruby"
]
}

+ Response 201 (application/json)

+ Headers

Location: /questions/2

+ Body

{
"question": "Favourite programming language?",
"published_at": "2015-08-05T08:40:51.620Z",
"choices": [
{
"choice": "Swift",
"votes": 0
}, {
"choice": "Python",
"votes": 0
}, {
"choice": "Objective-C",
"votes": 0
}, {
"choice": "Ruby",
"votes": 0
}
]
}

Here is the full example code

   FORMAT: 1A
HOST: https://polls.apiblueprint.org/

# Poll

Polls is a simple API allowing consumers to view polls and vote in them.

## Questions Collection [/questions]

### List All Questions [GET]

+ Response 200 (application/json)

[
{
"question": "Favourite programming language?",
"published_at": "2015-08-05T08:40:51.620Z",
"choices": [
{
"choice": "Swift",
"votes": 2048
}, {
"choice": "Python",
"votes": 1024
}, {
"choice": "Objective-C",
"votes": 512
}, {
"choice": "Ruby",
"votes": 256
}
]
}
]

### Create a New Question [POST]

You may create your own question using this action. It takes a JSON
object containing a question and a collection of answers in the
form of choices.

+ Request (application/json)

{
"question": "Favourite programming language?",
"choices": [
"Swift",
"Python",
"Objective-C",
"Ruby"
]
}

+ Response 201 (application/json)

+ Headers

Location: /questions/2

+ Body

{
"question": "Favourite programming language?",
"published_at": "2015-08-05T08:40:51.620Z",
"choices": [
{
"choice": "Swift",
"votes": 0
}, {
"choice": "Python",
"votes": 0
}, {
"choice": "Objective-C",
"votes": 0
}, {
"choice": "Ruby",
"votes": 0
}
]
}

Preview Documentation on Apiary

Apairy preview

Tools for API Blueprint

  • Apiary: Provides interactive documentation, API mocking, testing suites, and collaboration features.

  • Dredd: This tool Validates API implementations against the API Blueprint specification. It can generate test cases based on the API Blueprint.

  • Drakov: A mock server that implements API Blueprint specifications. It is useful for testing and development.

To learn more about API Blueprint tools, visit API Blueprint tools.

Assignment

Use a Swagger editor (like SwaggerHub, Editor.Swagger.io) to create an OpenAPI Specification (OAS) document for the TDMB API. The document should include the following elements:

  • Info: Basic information about the API (title, description, version, contact, license).
  • Paths: Define the API endpoints and their supported HTTP methods (GET, POST, PUT, DELETE).
  • Parameters: Describe query parameters, path parameters, and request bodies for each operation.
  • Responses: Define the expected responses for each operation, including status codes and response schemas.
  • Data Models: Create schemas to represent the data structures used by the API.
  • Security: If authentication is required, specify the security scheme (e.g., API Key, OAuth2) and how it is used.

Documentation Preview and Generation: Use Swagger tools to preview the generated API documentation. This will give you an interactive view of the API, similar to what developers will see when using it.

Write a reflection on the experience of documenting the TDMB API using Swagger. Include the following:

  • Challenges you faced.
  • Key lessons learned about API documentation and Swagger.

Lastly, after review, tag @Technicalwrit6 on Twitter and LinkedIn, stating that this is your API Specification assignment.