Use Cases (अपडेट: 3/6/2026)

Claude Code और AWS API Gateway: SAM से HTTP API, CORS, logs, auth और throttling

Claude Code से AWS API Gateway बनाएं: SAM, CORS, logs, auth review और throttling के उदाहरण।

Claude Code और AWS API Gateway: SAM से HTTP API, CORS, logs, auth और throttling

API Gateway आपकी public API का मुख्य प्रवेश द्वार है

AWS API Gateway वह layer है जो बाहर से आने वाली API requests को स्वीकार करती है और authentication, rate limits, logs और backend connection को एक जगह संभालती है। Browser, mobile app, partner system या internal job एक URL call करता है। API Gateway route पहचानता है, access check करता है, access log लिखता है और request को Lambda, HTTP endpoint या किसी AWS service तक भेजता है।

Claude Code के साथ यह समझ बहुत जरूरी है। अगर prompt सिर्फ “एक API बना दो” है, तो Claude Code चलने वाली Lambda बना सकता है, लेकिन CORS, JWT या IAM authentication, access logs, throttling, stage name और HTTP API बनाम REST API का निर्णय छूट सकता है। Demo में सब ठीक लगता है, पर production में frontend CORS से रुकता है या incident के समय requestId नहीं मिलता।

इस guide में AWS official documentation को आधार बनाकर AWS SAM का copy-paste example दिया गया है। लक्ष्य केवल API चलाना नहीं है; लक्ष्य ऐसी API Gateway बनाना है जिसे Claude Code review कर सके और team production में चला सके।

REST API, HTTP API या WebSocket API चुनना

API Gateway के तीन आम रूप हैं: REST API, HTTP API और WebSocket API। AWS इसे client को Lambda, HTTP backend और AWS services से जोड़ने वाली API creation और management service के रूप में बताता है।

प्रकारकब उपयोग करेंव्यावहारिक निर्णय
HTTP APISPA, mobile और Lambda आधारित JSON APIकम cost, कम latency, JWT, CORS, logs और simple routes चाहिए तो पहले यही चुनें
REST APIadvanced API managementAPI keys, usage plans, request validation, WAF, private endpoint या client-specific limits चाहिए तो चुनें
WebSocket APItwo-way communicationchat, notifications, live progress या server push के लिए

AWS की comparison documentation बताती है कि REST API में अधिक features हैं, जबकि HTTP API छोटा और सस्ता product है। Contact form, booking, webhook या simple Lambda API के लिए HTTP API अक्सर काफी है। API key, customer plan, WAF या private access आने पर REST API पर विचार करें।

Official references:

Code से पहले चार use cases तय करें

पहला use case Lambda integration है। API Gateway public URL और routing संभालता है। Lambda business logic संभालती है। Contact form, booking form, SaaS webhook और छोटी internal API में यह pattern साफ रहता है।

दूसरा use case CORS है। अगर frontend https://example.com पर है और API execute-api domain पर है, तो browser इन्हें अलग origin मानता है। AWS documentation बताती है कि HTTP API में CORS configuration preflight OPTIONS request का जवाब दे सकती है। यह भी बताया गया है कि API level CORS होने पर backend integration से आए CORS headers ignore हो सकते हैं। इसलिए CORS को Lambda में बिखेरने के बजाय API Gateway में design करें।

तीसरा use case authentication है। JWT authorizer Cognito या OIDC token वाले user APIs के लिए ठीक है। IAM authorization AWS workloads के लिए ठीक है, जहां SigV4 signed request और execute-api permission चाहिए। Lambda authorizer तब उपयोग करें जब legacy user database, partner contract, IP restriction या complex permission logic हो।

चौथा use case operations है। CloudWatch access logs में requestId, routeKey, status, IP और time होना चाहिए। Throttling excess requests को 429 Too Many Requests दे सकता है, लेकिन इसे absolute wall न मानें। Lambda concurrency, database limits और client backoff भी design करें।

Copy-paste AWS SAM example

template.yaml बनाएं।

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Claude Code Lab HTTP API sample with CORS, logs, throttling, and Lambda proxy

Parameters:
  StageName:
    Type: String
    Default: Prod
  AllowedOrigin:
    Type: String
    Default: https://example.com

Globals:
  Function:
    Runtime: nodejs20.x
    Architectures:
      - arm64
    Timeout: 10
    MemorySize: 256

Resources:
  ApiAccessLogs:
    Type: AWS::Logs::LogGroup
    Properties:
      RetentionInDays: 14

  PublicHttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      StageName: !Ref StageName
      CorsConfiguration:
        AllowOrigins:
          - !Ref AllowedOrigin
        AllowHeaders:
          - authorization
          - content-type
          - x-request-id
        AllowMethods:
          - GET
          - POST
          - OPTIONS
        MaxAge: 300
      AccessLogSettings:
        DestinationArn: !GetAtt ApiAccessLogs.Arn
        Format: '{"requestId":"$context.requestId","routeKey":"$context.routeKey","status":"$context.status","ip":"$context.identity.sourceIp","requestTime":"$context.requestTime","responseLength":"$context.responseLength"}'
      DefaultRouteSettings:
        ThrottlingBurstLimit: 20
        ThrottlingRateLimit: 10
      RouteSettings:
        "POST /contacts":
          ThrottlingBurstLimit: 5
          ThrottlingRateLimit: 2
      FailOnWarnings: true

  HealthFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.health
      Events:
        Health:
          Type: HttpApi
          Properties:
            ApiId: !Ref PublicHttpApi
            Path: /health
            Method: GET
            PayloadFormatVersion: "2.0"

  ContactFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.contact
      Events:
        Contact:
          Type: HttpApi
          Properties:
            ApiId: !Ref PublicHttpApi
            Path: /contacts
            Method: POST
            PayloadFormatVersion: "2.0"
            TimeoutInMillis: 10000

Outputs:
  ApiUrl:
    Description: Invoke URL
    Value: !Sub "https://${PublicHttpApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}/${StageName}/"

package.json और src/handler.js जोड़ें।

{
  "type": "module",
  "scripts": {
    "check": "node --check src/handler.js"
  }
}
const json = (statusCode, body) => ({
  statusCode,
  headers: { "content-type": "application/json" },
  body: JSON.stringify(body)
});

export const health = async () => json(200, {
  ok: true,
  service: "claude-code-api-gateway",
  checkedAt: new Date().toISOString()
});

export const contact = async (event) => {
  let payload;
  try {
    payload = JSON.parse(event.body ?? "{}");
  } catch {
    return json(400, { message: "Request body must be valid JSON." });
  }

  const name = String(payload.name ?? "").trim();
  const email = String(payload.email ?? "").trim();
  if (!name || !email.includes("@")) {
    return json(422, { message: "name and a valid email are required." });
  }

  return json(202, {
    message: "accepted",
    requestId: event.requestContext?.requestId,
    received: { name, email }
  });
};

Run करें:

npm run check
sam build
sam deploy --guided \
  --stack-name clc-api-gateway-sample \
  --parameter-overrides AllowedOrigin=https://example.com

Claude Code review prompt

Production से पहले इस AWS SAM template को review करें।
Public routes, बहुत broad CORS, missing JWT/IAM/Lambda authorizer,
requestId या routeKey के बिना access logs, कमजोर throttling,
unsafe Lambda error responses और REST API की जरूरत वाले requirements खोजें।
Concrete template changes दें।

Common failures

पहली गलती CORS को केवल Lambda में रखना है। HTTP API में API Gateway CORS setting को मुख्य source मानें।

दूसरी गलती access logs को बाद के लिए छोड़ना है। कई 403, 404 और 429 Lambda तक पहुंचने से पहले होते हैं।

तीसरी गलती throttling को perfect hard limit समझना है। Lambda, database, queue और client retry भी protect करें।

चौथी गलती आदत से API type चुनना है। HTTP API बहुत उपयोगी है, लेकिन API keys, usage plans, WAF और private endpoint के लिए REST API चाहिए हो सकती है।

आगे पढ़ने के लिए Claude Code AWS Lambda, Claude Code AWS CloudWatch और Claude Code AWS IAM देखें। Practical team material training page पर है।

Masa ने क्या test किया

Masa ने इस flow को design, template, Lambda और review में बांटकर test किया। Claude Code ने सबसे उपयोगी बातों में POST /contacts के लिए /health से strict throttling, logs में requestId और routeKey, और public route को temporary state मानना बताया। API Gateway boundary से शुरू करने पर Lambda code आसान और review साफ हुआ।

#claude-code #aws #api-gateway #lambda #typescript #rest-api
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.