LoginSignup
1
0

【AWS】APIKeyを使用したAPIGatewayの設定備忘録

Last updated at Posted at 2024-01-02

 顧客へのAPIをサービスとして提供するには、API Gateway 使用量プランを設定する。API Gateway 使用量プランは、API キーを設定し、キーを知っているユーザーのみ利用可能にし、API キーでリクエストユーザーを特定することで、定義した制限とクォータに基づいて、スロットリングすることができる。今回は、LambdaとAPIGatewayを用いた使用料プラン付きのAPI作成方法を紹介する。

Lambda + APIGatewayでAPIkey作成

  1. 適当にLambda関数を作成する
  2. トリガーを追加で、APIGateway、API type = RestAPI、Security = APIKeyを選択する
  3. 作成したAPIgatewayをコンソール画面で開く
  4. ステージを開き、CORSを有効にして、デプロイする
    APIGateway12.PNG
  5. APIKeyを確認する
    APIGateway11.PNG

Curlで検証してみる

curl -X POST https://******************* --header "x-api-key:cLXRV9Enox6AJkzdCViKP52xdMGcA1Sj9QaLzjxR"

React/axiosでリクエストしてみる

  const handleGetSubmission = async () => {
    const users = await Auth.currentAuthenticatedUser()
    const username = users.username + '-' + countryCode
    const body = {
      user: username
    }
    try {
      await axios
        .post(
          'https://*********************',
          body,
          {
            headers: {
              'Content-type': 'text/plain',
              'x-api-key': 'mtpJPQpxRha1SbL2QpC3X5cT8ZygXzY65AQqLRXJ',
            },
          },
        )
        .then((res) => {
          console.log(res.data)
        })
    } catch (err) {
      console.error(err.message)
    }
  }

参考文献

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