Building RESTful API specification with OpenAPI
![]()
Before knowing about OpenAPI, I have struggled with defining data types for FrontEnd and BackEnd manually. Any mismatch between them can cause errors. When OpenAPI comes, I only need to define it once and use it for both sides. This post will bring you a brief look about OpenAPI.
この記事の目次
What is OpenAPI?
OpenAPI is a specification for building and describing RESTful APIs, allowing developers to define their API’s structure in a standardized format that can be easily understood and used by both humans and machines. It allows developers to define their API endpoints, request/response formats, authentication methods, and more in a machine-readable format, typically using a JSON or YAML file.
Features
Standardization: Provides a consistent and standardized way to describe APIs, making it easier for developers to understand and work with APIs.
Documentation: Tools like Swagger UI and Redoc can automatically generate interactive documentation from an OpenAPI file, making it easier for developers to explore and test the API.
Code generation: OpenAPI can be used to generate server stubs, client SDKs, and API documentation, reducing the amount of manual coding required.
Validation: Ensures that API requests and responses conform to the defined specification, which helps in maintaining consistency and quality.
Create an OpenAPI specification
I will use YAML format to define the specification. There are a lot of options so I will list some frequently used options.
Header
openapi: Specify openAPI version. Current version is 3.0.3.
info: Describe information about this API specification like title, description, version, etc.
servers: Specify server configuration like url, base path, protocol, etc. We can define multiple servers.
Example:
openapi: 3.0.3
info:
title: Bookstore API
description: Bookstore API example
license:
name: Apache 2.0
url: http://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.0
servers:
- url: https://mybookstore.com/api/v1
API list
API urls are listed below the paths option. Below is information for a url api.
{url}: this api url
get/post/put/delete: request method
parameters: define query or path parameters
requestBody: define request body. It can be in any format JSON, xml, x-www-form-urlencoded, etc.
responses: define response. It can have many formats the same as the request body.
security: define security requirements for this api url.
Example:
paths:
/books:
get:
operationId: getBooks
description: Get book list
parameters:
- name: available
in: query
description: Find available books
required: false
explode: true
schema:
type: boolean
default: false
responses:
'200':
description: Successful operation
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Book'
'400':
description: Invalid operation
'401':
description: Unauthorized
security:
- bearerAuth: []
Component
Components are listed below the components option.
schemas: define data object for request and response
securitySchemes: define security schema.
Example:
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
Book:
type: object
properties:
id:
type: integer
format: int64
example: 10
title:
type: string
example: Awesome book
price:
type: integer
example: 100
available:
type: boolean
updateDate:
type: string
format: date-time
Generate code and tools
There are many tools and Command-line interface (CLI) libraries that you can use to generate code from specification. Below is a sample specification. You can paste it to Swagger Editor . You will get visualization of the API.
openapi: 3.0.3
info:
title: Bookstore API
description: Bookstore API example
license:
name: Apache 2.0
url: http://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.0
servers:
- url: https://mybookstore.com/api/v1
paths:
/books:
get:
operationId: getBooks
description: Get book list
parameters:
- name: available
in: query
description: Find available books
required: false
explode: true
schema:
type: boolean
default: false
responses:
'200':
description: Successful operation
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Book'
'400':
description: Invalid operation
'401':
description: Unauthorized
security:
- bearerAuth: []
post:
operationId: postBook
description: Create new book
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Book'
responses:
'200':
description: successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/Book'
'400':
description: Invalid operation
'401':
description: Unauthorized
security:
- bearerAuth: []
/books/{id}:
get:
operationId: getBookDetail
description: Get book detail
parameters:
- name: id
in: path
description: Book id
required: true
explode: true
schema:
type: integer
responses:
'200':
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/Book'
'400':
description: Invalid operation
'401':
description: Unauthorized
security:
- bearerAuth: []
put:
operationId: putBook
description: Update book information
parameters:
- name: id
in: path
description: Book id
required: true
explode: true
schema:
type: integer
responses:
'200':
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/Book'
'400':
description: Invalid operation
'401':
description: Unauthorized
security:
- bearerAuth: []
delete:
operationId: deleteBook
description: delete a book
parameters:
- name: id
in: path
description: Book id
required: true
explode: true
schema:
type: integer
responses:
'204':
description: Book was deleted
'400':
description: Invalid operation
'401':
description: Unauthorized
security:
- bearerAuth: []
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
Book:
type: object
properties:
id:
type: integer
format: int64
example: 10
title:
type: string
example: Awesome book
price:
type: integer
example: 100
available:
type: boolean
updateDate:
type: string
format: date-time
![]()
Result of API specification
To generate code for Backend/Frontend you can click Generate Server/Generate Client and choose the desired language. I will choose typescript-axios in this example.
![]()
Generate typescript axios code
Swagger will generate code with configuration and pack to a zip file. Now you can extract and copy them to your project folder.
![]()
Generated book.ts file
If you want to generate code from CLI you can use OpenAPI Generator (openapi-generator.tech) .
Install and generate command:
npm install @openapitools/openapi-generator-cli -g openapi-generator-cli generate -i bookAPI.yaml -g typescript-axios -o output
Summary
Creating API specifications can be difficult and time consuming at first. But it minimizes type errors between Frontend and Backend. Maintenance time is also reduced thanks to the generation feature. Let’s give it a try, you can improve your project quality!
References:
Home 2024 – OpenAPI Initiative (openapis.org)
API Documentation & Design Tools for Teams | Swagger
Hello from OpenAPI Generator | OpenAPI Generator (openapi-generator.tech)
この情報は役に立ちましたか?
カテゴリー: