TypeSpecからAmazon API GatewayにインポートできるOpenAPIを生成する

TypeSpecからAmazon API GatewayにインポートできるOpenAPIを生成する
この記事をシェアする

本記事では、TypeSpecで記述したAPI仕様からAmazon API Gatewayにインポート可能なOpenAPIを生成する方法を紹介します。複雑な設定は省き、Lambda統合とCognito認証を含む構成を作成していきます。

この記事の要約

  • ゴール: TypeSpecからAPI Gateway拡張付きOpenAPIを生成し、API Gatewayへインポートする。
  • 焦点: x-amazon-apigateway-integrationなどの、API Gateway独自拡張のTypeSpecでの書き方。
  • 構成: API Gateway + Lambda統合、Cognitoユーザプール認証を前提とする。
  • デモ: Codespacesで動作し、CDKで即デプロイできる(AWSアカウントとインフラ費用が必要)。
  • 参考: 公式ドキュメントのURLを随所で併記する。

TypeSpecとは?

TypeSpecはMicrosoftが開発したAPI仕様記述言語で、OpenAPIやJSON Schema、Protobuf等へ変換できます。

  • 利点: 型安全、再利用性が高い、多形式出力、IDEサポートが充実。
  • 公式: TypeSpec Docs / GitHub

API GatewayのOpenAPI拡張とは?

API GatewayはOpenAPIに独自拡張を定義し、Lambda統合や認証などの設定を記述できます。

API GatewayにはOpenAPIをインポートして、APIを作成する「インポート機能」があります。インポート機能では、OpenAPIファイルに上記の拡張を記述することで、統合や認証設定をワンストップで作成できます。

今回のデモ構成とリポジトリ

  • アーキテクチャ: API Gateway → Lambda(統合)/ Cognito(ユーザプール認証)
  • デモリポジトリ: demo_typespec_apigateway_openapi_extension(リンク)
    • 手順: README.mdを参照
      • CDKで、ARN部分の置換(後述)やAWSへのデプロイまで自動化しています。
    • 注意: Codespacesで動作。デプロイにAWSアカウントと費用が必要です。

TypeSpecサンプルコード全文とOpenAPI変換結果

最初に、TypeSpecサンプルコード全文と、変換後のOpenAPIファイルを提示します。追って、各パートを説明していきます。


import "@typespec/http";
import "@typespec/rest";
import "@typespec/openapi";
import "@typespec/openapi3";
import "@typespec/compiler";

using Http;
using OpenAPI;

@service(#{title: "Demo API"})
@useAuth(CognitoAuthorizer)
namespace DemoService;

@extension("x-amazon-apigateway-authtype", "cognito_user_pools")
@extension("x-amazon-apigateway-authorizer", #{
  type: "cognito_user_pools",
  providerARNs: #["__COGNITO_USERPOOL_ARN__"],
})
model CognitoAuthorizer is ApiKeyAuth<ApiKeyLocation.header, "Authorization">;

model Message {
  content: string;
}

@error
model Error {
  code: int32;
  message: string;
}

@route("/hello")
interface Hello {
  @get
  @tag("Default")
  @extension("x-amazon-apigateway-integration", #{ 
    type: "aws_proxy",
    httpMethod: "POST",
    uri: "__LAMBDA_INTEGRATION_URI__",
    passthroughBehavior: "when_no_match",
    contentHandling: "CONVERT_TO_TEXT",
    timeoutInMillis: 29000,
  })
  get(): Message | Error;
}
openapi: 3.0.0
info:
  title: Demo API
  version: 0.0.0
tags:
  - name: Default
paths:
  /hello:
    get:
      operationId: Hello_get
      parameters: []
      responses:
        '200':
          description: The request has succeeded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Message'
        default:
          description: An unexpected error response.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      tags:
        - Default
      x-amazon-apigateway-integration:
        type: aws_proxy
        httpMethod: POST
        uri: __LAMBDA_INTEGRATION_URI__
        passthroughBehavior: when_no_match
        contentHandling: CONVERT_TO_TEXT
        timeoutInMillis: 29000
security:
  - CognitoAuthorizer: []
components:
  schemas:
    CognitoAuthorizer:
      type: object
      required:
        - type
        - in
        - name
      properties:
        type:
          type: string
          enum:
            - apiKey
          description: API key authentication
        in:
          type: string
          enum:
            - header
          description: location of the API key
        name:
          type: string
          enum:
            - Authorization
          description: name of the API key
      description: ''
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          - __COGNITO_USERPOOL_ARN__
      x-amazon-apigateway-authtype: cognito_user_pools
    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    Message:
      type: object
      required:
        - content
      properties:
        content:
          type: string
  securitySchemes:
    CognitoAuthorizer:
      type: apiKey
      in: header
      name: Authorization
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          - __COGNITO_USERPOOL_ARN__
      x-amazon-apigateway-authtype: cognito_user_pools

TypeSpecとLambda統合の付与

@extensionでOpenAPIのベンダー拡張を直接埋め込み、各オペレーションにLambda統合を付与します。

参考: @extensionのリファレンス

@route("/hello")
interface Hello {
  @get
  @tag("Default")
  @extension("x-amazon-apigateway-integration", #{ 
    type: "aws_proxy",
    httpMethod: "POST",
    uri: "__LAMBDA_INTEGRATION_URI__",
    passthroughBehavior: "when_no_match",
    contentHandling: "CONVERT_TO_TEXT",
    timeoutInMillis: 29000,
  })
  get(): Message | Error;
}

変換後のOpenAPIでは、エンドポイントに対して、x-amazon-apigateway-integration拡張が付与されていることがわかります。

paths:
  /hello:
    get:
      operationId: Hello_get
      parameters: []
      responses:
        '200':
          description: The request has succeeded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Message'
        default:
          description: An unexpected error response.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      tags:
        - Default
      x-amazon-apigateway-integration:
        type: aws_proxy
        httpMethod: POST
        uri: __LAMBDA_INTEGRATION_URI__
        passthroughBehavior: when_no_match
        contentHandling: CONVERT_TO_TEXT
        timeoutInMillis: 29000
  • uriはAPI Gateway→Lambdaの統合URI形式で、上記の__LAMBDA_INTEGRATION_URI__をarn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/<Lambda関数のARN>/invocationsに置き換える必要があります。
    • 手動で置き換えても良いし、なんらかの方法で自動化しても良いです。
      • デモでは、CDKの実行時に置き換えています。
  • 参考:x-amazon-apigateway-integration拡張の仕様

Cognitoユーザプール認証を付与する

TypeSpecでは、@useAuthで認証オブジェクトを指定することで、認証を設定できます。認証の範囲は下記のサンプルコードでは、トップのnamespaceに対して@useAuthを指定しているので、API全体となります。このほかに、オペレーション単位にすることもできます。

@service(#{title: "Demo API"})
@useAuth(CognitoAuthorizer)
namespace DemoService;

@extension("x-amazon-apigateway-authtype", "cognito_user_pools")
@extension("x-amazon-apigateway-authorizer", #{
  type: "cognito_user_pools",
  providerARNs: #["__COGNITO_USERPOOL_ARN__"],
})
model CognitoAuthorizer is ApiKeyAuth<ApiKeyLocation.header, "Authorization">;

変換後のOpenAPIでは、components.securitySchemesに、再利用可能な認証設定が定義されています。さらに、この認証設定を、トップレベルのsecurityから呼び出す記述になっています。これにより、API全体がCognitoAuthorizerで保護されることになります。

security:
  - CognitoAuthorizer: []
# 中略
components:
  # 中略
  securitySchemes:
    CognitoAuthorizer:
      type: apiKey
      in: header
      name: Authorization
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          - __COGNITO_USERPOOL_ARN__
      x-amazon-apigateway-authtype: cognito_user_pools

わからなかったこと

変換後のOpenAPIに不要な記述が入ってしまいました。

components:
  schemas:
    CognitoAuthorizer:
      type: object
      required:
        - type
        - in
        - name
      properties:
        type:
          type: string
          enum:
            - apiKey
          description: API key authentication
        in:
          type: string
          enum:
            - header
          description: location of the API key
        name:
          type: string
          enum:
            - Authorization
          description: name of the API key
      description: ''
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          - __COGNITO_USERPOOL_ARN__
      x-amazon-apigateway-authtype: cognito_user_pools

これは、TypeSpec側で認証設定をmodel CognitoAuthorizerのようにmodelとして定義したことによるものだと思います。ここでmodelとして定義した理由は、この認証設定に@extensionを付与した上で、useAuthで使用必要があったからです。

このmodelはAPI利用者が意識するものではないので、OpenAPIファイルからは削除したいのですが、いい方法が思いつきませんでした……。

さいごに

  • TypeSpecでAPIを一元管理しつつ、API Gateway拡張を@extensionで付与してOpenAPIを生成できました。
  • Lambda統合とCognito認証の構成をOpenAPIインポートで構築する手順を整理しました。
この記事をシェアする
著者:酒井亮太郎
シナモロール