1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenAPIについて調べてみた。

Posted at

#はじめに
最近gRPCやOpenAPIなどのコード生成ツールが気になってるので雑に調べてみた。

OpenAPIの歴史

OpenAPIは、もともとSwaggerとして知られていました。Swaggerは、2010年に開始され、REST APIの定義、ドキュメンテーション、そしてクライアントSDK生成のためのフレームワークとして急速に普及しました。2015年、Swaggerの仕様はLinux Foundationに寄贈され、OpenAPI Initiative (OAI) が設立されました。

OpenAPIの主な特徴

  1. 標準化: APIのエンドポイント、パラメータ、レスポンス、セキュリティの定義など、RESTful APIに関連する多くの側面を標準化します。
  2. バージョニング: APIのバージョン管理をサポートします。
  3. 再利用可能なコンポーネント: 同じ定義を複数の場所で再利用することができます。

詳細な記述例

openapi: 3.0.0
info:
  title: User API
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
security:
  - ApiKeyAuth: []
paths:
  /users:
    get:
      summary: Get all users
      tags:
        - Users
      parameters:
        - name: limit
          in: query
          required: false
          description: Max number of results to return
          schema:
            type: integer
            format: int32
            minimum: 1
            maximum: 100
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
        '400':
          description: Bad request
        '401':
          description: Unauthorized
        '404':
          description: Not found
        '500':
          description: Server error
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-KEY
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int32
          description: Unique identifier for the user
        name:
          type: string
          description: Full name of the user
          maxLength: 255

このOpenAPIの定義は、ユーザ情報を取得するAPIを表現しています。APIのエンドユーザは、単一のエンドポイント/usersにアクセスすることでユーザ情報を取得できます。要求する際、リクエストのヘッダーにX-API-KEYという名前でAPIキーを提供すること。

OpenAPIとツールの連携

OpenAPIの仕様は多くのツールと連携することができます。例えば:

  1. Swagger UI: 仕様からインタラクティブなAPIドキュメントを生成します。
  2. Redoc: 高度なビジュアルでAPIドキュメントを表示します。
  3. Swagger Codegen: 仕様からクライアントやサーバのコードを自動生成します

活用シーンとベストプラクティス

  1. APIの設計時: OpenAPIでAPIの仕様を最初から定義することで、開発の方針を明確にし、チーム内でのコミュニケーションを促進します。
  2. ドキュメントの自動生成: OpenAPIを使ってドキュメントを自動生成することで、ドキュメントのメンテナンスコストを削減できます。
  3. モックサーバーの利用: OpenAPI仕様からモックサーバーを立てることで、フロントエンドの開発やAPIのテストが効率的に行えます。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?