Files
floci/docs/services/api-gateway.md
T
Sam Fakhreddine 9b9e7f56a2 feat(apigateway): API key import/usage-plan fidelity and update-operation fixes (#2631)
* feat(apigateway): complete the REST API resource lifecycle

Adds the missing delete and update operations across authorizers,
integrations, integration responses, methods, method responses, models,
request validators, resources, rest APIs, stages, deployments, domain names
and base path mappings, plus tag/untag, usage plan and usage plan key CRUD,
and ImportApiKeys backed by a new ApiKeyCsvParser.

Each operation has a wire-level integration test.

* feat(apigatewayv2): allow clearing an HTTP API CORS configuration

deleteCorsConfiguration unsets the optional CORS block on a stored API so
the response omits it rather than echoing a stale configuration.

* fix(apigateway): accept the AWS-native ImportApiKeys CSV format

The header validator required exactly `name,value,enabled` in lowercase and
read every row by fixed position. Real AWS ships `Name,Key,Description,
Enabled,UsagePlanIds`, so the CLI, SDKs and Terraform all took a 400 on their
first call. Columns are now resolved case-insensitively by name into an index
map, `value` is kept as an alias for `Key`, a missing or blank `Enabled`
defaults to true as AWS does, and rows shorter than the header no longer throw.

Imported keys are also created with generateDistinctId, because the CSV `Key`
column is the key VALUE and AWS generates the id separately — reusing the value
as the id let one row silently clobber an existing key and detach its usage
plan associations.

ImportApiKeys now reports warnings for real: a row whose key value duplicates an
earlier row in the same import raises one, and `failonwarnings=true` turns those
warnings into a BadRequestException instead of being ignored.

* fix(apigateway): honour the patchOperations envelope on UpdateModel and UpdateUsagePlan

Both handlers parsed the PATCH body as a flat map. Real AWS sends
`{"patchOperations":[{"op":"replace","path":"/description","value":"x"}]}`, so
the flat parse succeeded, matched nothing, and returned the untouched resource
with a 200 — a silent no-op. Both now walk the ops list the way the six sibling
endpoints in this controller already do.

UpdateModel supports /description, /schema and /contentType, and rejects /name
with a BadRequestException: AWS treats a model name as an immutable identifier.
That also removes the delete-then-put rename, which had no existence check on
the target key and so destroyed any model already using the new name.

UpdateUsagePlan supports /name, /description and add/remove of /apiStages as
"apiId:stage", covering what the flat handler could do. UsagePlan carries no
throttle or quota state, so those paths are left unsupported rather than faked.

UpdateAuthorizer now parses /authorizerResultTtlInSeconds before mutating
anything. A non-numeric value used to be written straight to the store, after
which serialisation threw on the PATCH and on every later GetAuthorizer and
GetAuthorizers for that resource — unrecoverable short of delete and recreate.

* fix(apigateway): reject duplicate sibling paths and bad parentId on resources

UpdateResource pointed at an unknown /parentId surfaced getResource's 404
"Invalid resource id specified", which reads as though the resource being
patched is missing; the `parent == null` guard beneath it was unreachable for
the same reason. AWS answers 400, so the lookup failure is now rethrown as a
BadRequestException naming the offending value.

Neither CreateResource nor UpdateResource checked for a sibling collision, so
two children of one parent could end up with the same path and request routing
became order-dependent. Both now go through a shared guard that raises
ConflictException (409) when another child of the effective parent already uses
that pathPart.

UpdateResource also stopped mutating as it goes. The store hands back live
objects, so applying ops in-place meant a later rejected op left the earlier
ones visible in memory; the patch is now resolved into pending parentId and
pathPart values, validated, and only then applied.

* style(apigateway): put HttpHeaders first in deleteAuthorizer

Every other handler in the controller takes @Context HttpHeaders as its first
parameter. No behaviour change.

* fix(apigateway): answer BadRequestException for a malformed patchOperations envelope

The PATCH handlers parsed the envelope with convertValue(node, List.class)
inside a catch that only covered IOException. convertValue throws
IllegalArgumentException, which no mapper handles, so a non-array
patchOperations returned 500 instead of the modelled BadRequestException.
The raw List.class conversion also deferred a structured operation value
into the service layer as a ClassCastException, a second 500.

Extract one parsePatchOperations helper that converts through a
TypeReference<List<Map<String, String>>> and widens the catch, so scalar
values coerce and structured ones are rejected at the boundary.

* fix(apigateway): dispatch ImportApiKeys on mode, not on media type

ImportApiKeys was annotated @Consumes("text/csv"), but botocore sends the
operation with no Content-Type header at all — only Accept: application/json.
A request with no Content-Type is application/octet-stream to JAX-RS, so it
never matched, and fell through to the sibling CreateApiKey handler, which
fed the CSV body to the JSON parser and answered a spurious
BadRequestException. Every existing test hid this by setting text/csv
explicitly, a header no client sends.

Fold both operations into one POST /apikeys handler that consumes any media
type and tells them apart by the mode query parameter, the way AWS does, and
cover it with a raw-client case that sends no Content-Type.

* docs(apigateway): document the operations this branch added

The branch added 13 v1 management operations and DeleteCorsConfiguration on
v2 without touching docs, and the Not Implemented list still named
UpdateAuthorizer, DeleteAuthorizer, ImportApiKeys, GetUsagePlan,
UpdateUsagePlan and UpdateModel as absent. GetDeployment and DeleteDeployment
were already implemented but had never been listed either.

api-gateway.md is hand-maintained — ApiGatewayController is a REST controller
and is not registered in tools/docs/services.yaml — so the tables are updated
by hand and the index counts follow the tables: v1 64 -> 79, v2 48 -> 49.
Also record how CreateApiKey and ImportApiKeys share POST /apikeys.

* fix(apigateway): extend the patchOperations boundary parse to the inherited handlers

Six PATCH handlers predate this branch and still parsed the envelope with
convertValue(node, List.class) inside an IOException-only catch, so
updateRestApi, updateResource, updateMethod, updateIntegration, updateStage
and updateApiKey kept answering 500 for a malformed envelope while the eight
handlers this branch added answered 400. A reviewer would rightly ask why
only some of the surface agrees with AWS.

This is a deliberate scope extension beyond the audit's finding: point all
six at the existing parsePatchOperations helper so every PATCH operation on
the service shares one boundary contract. updateAccount stays as it is — it
validates each operation itself and already raises a modelled 400.

* docs(apigatewayv2): correct the VPC Link operations, which are implemented

The v2 Not Implemented list named all five VPC Link operations as absent, but
CreateVpcLink, GetVpcLink, GetVpcLinks and DeleteVpcLink have been routed on
/v2/vpclinks and backed by ApiGatewayV2Service since before this branch. Only
UpdateVpcLink is genuinely missing — there is no PATCH route for it.

Verified each claimed route against ApiGatewayController before editing. Adds
the VPC Links row the v2 table never had and carries the four operations into
the index count: 49 -> 53.

* fix(apigateway): enforce the modelled op enum on patchOperations

Botocore models PatchOperation.op as an enum of add, remove, replace,
move, copy and test. The boundary parse read the envelope's shape but
never the op value, and the handlers behind it disagree about what to do
with an unrecognised one: UpdateModel throws, UpdateApiKey and UpdateStage
skip it. On the skipping handlers an unmodelled op was answered 200 with
the resource untouched, which reads to the caller as an applied patch.

Check op against the enum in parsePatchOperations, the boundary this
branch already made responsible for the envelope on every PATCH handler.
The set is the model's, not the intersection of what the handlers
implement: whether a handler supports move is its own business, but a
value outside the enum should never reach one.

* fix(apigateway): reject a null element in the patchOperations envelope

parsePatchOperations silently skipped a null element in the patchOperations
array instead of rejecting it. Several handlers that predate the shared
boundary parse (updateRestApi, updateStage, updateApiKey, updateMethod) have
no null guard of their own and call op.get("op") directly, so a null element
reached them as an unhandled NullPointerException -- a 500 instead of AWS's
modelled BadRequestException.

Reject the null at the boundary all handlers already share, the same place
that already validates the op enum.

* fix(apigateway): apply patchOperations atomically instead of partially

updateAuthorizer, updateUsagePlan, updateRequestValidator, updateModel,
updateDomainName and updateBasePathMapping mutated the live stored object as
each op was validated. The store hands back live objects (no defensive
copy), so a valid op followed by an invalid one left the valid op's change
visible even though the request answered 400 -- the same partial-apply bug
already fixed for updateResource in an earlier commit on this branch, which
established the fix: resolve every op into pending local values, validate
the whole list, and only mutate the stored object once the patch is known
to be entirely good.

Each handler also now rejects a null patchOperations element explicitly, on
top of the shared boundary's own rejection, matching the defensive style
already used by updateRequestValidator and updateModel before this change.

* fix(apigateway): translate a malformed ImportApiKeys CSV into BadRequestException

ApiKeyCsvParser.parse throws IllegalArgumentException on an unterminated
quoted field, but only AwsException is registered with an ExceptionMapper.
The unmapped exception escaped as a 500 instead of AWS's modelled 400,
letting a malformed import request past the error boundary entirely.

Catch the parser's IllegalArgumentException at the one call site and
translate it into the same BadRequestException every other CSV validation
failure in this method already raises.

* style(apigateway): brace the new conditionals this branch added

New single-line if statements in the domain-name serialization, CSV import
column/cell handling, and resource sibling-collision check violated the
repository's mandatory conditional-brace convention. No behaviour change.

* fix(apigateway): validate all UpdateIntegration patch ops before applying any

updateIntegration mutated the live stored integration inside the same loop that validated later operations, so a PATCH with a valid op followed by an unsupported path left the earlier op applied even though the request as a whole was rejected with 400.
2026-08-27 16:59:59 -04:00

17 KiB

API Gateway

Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs).

Custom API IDs

API IDs are generated randomly, which means endpoint URLs change every time you recreate an API. To pin one, pass the reserved floci:override-id tag on creation and Floci uses its value as the API ID. This works for both v1 (CreateRestApi) and v2 (CreateApi), and matches the tag other services such as KMS and Cognito already use.

aws apigateway create-rest-api \
  --name my-api \
  --tags '{"floci:override-id":"my-fixed-id","env":"test"}' \
  --endpoint-url http://localhost:4566
# the API is now reachable at the stable id "my-fixed-id"

The override key is consumed rather than stored, so it never appears in the tags the API returns. Any other tags in the same request are kept. Because an ID cannot change after creation, supplying either override key to TagResource is rejected with BadRequestException.

Values must be non-blank and must not contain whitespace, control characters, or /, ?, #, since those would break the endpoint URL. An invalid value is rejected with BadRequestException.

Creating a second API with an override ID that already exists in the region is rejected with ConflictException instead of overwriting the existing API, matching how KMS and Cognito treat duplicate override IDs.

Note

API Gateway previously used a _custom_id_ tag for this. It still works so existing setups keep running, and it is now stripped from the returned tags the same way, but it is deprecated: prefer floci:override-id. If both are present, floci:override-id wins, which lets you set both during a migration. The _custom_id_ key is API Gateway specific and is not reserved for any other service.

API Gateway v1 (REST APIs)

Protocol: REST JSON Endpoint: http://localhost:4566/restapis/...

Supported Operations

Category Operations
APIs CreateRestApi, ImportRestApi, PutRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi
Resources CreateResource, GetResource, GetResources, UpdateResource, DeleteResource
Methods PutMethod, GetMethod, UpdateMethod, DeleteMethod
Method Responses PutMethodResponse, GetMethodResponse, DeleteMethodResponse
Integrations PutIntegration, GetIntegration, UpdateIntegration, DeleteIntegration
Integration Responses PutIntegrationResponse, GetIntegrationResponse, UpdateIntegrationResponse, DeleteIntegrationResponse
Deployments CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment
Stages CreateStage, GetStage, GetStages, UpdateStage, DeleteStage
Authorizers CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer
API Keys CreateApiKey, ImportApiKeys, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey
Usage Plans CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan
Usage Plan Keys CreateUsagePlanKey, GetUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey
Request Validators CreateRequestValidator, GetRequestValidator, GetRequestValidators, UpdateRequestValidator, DeleteRequestValidator
Models CreateModel, GetModel, GetModels, UpdateModel, DeleteModel
Domain Names CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName
Base Path Mappings CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, UpdateBasePathMapping, DeleteBasePathMapping
Account GetAccount, UpdateAccount
Tags TagResource, UntagResource, GetTags (ListTagsForResource)

API Key Behaviour Notes

CreateApiKey and ImportApiKeys share one route

Both operations are POST /apikeys, and AWS tells them apart by the query string, not by Content-Type: ImportApiKeys carries ?mode=import&format=csv and a CSV body, CreateApiKey carries no query parameters and a JSON body. The SDKs send ImportApiKeys with no Content-Type header at all, so Floci accepts any media type on this route and dispatches on mode.

The CSV header row is addressed by name, not position. AWS's own column set is Name,Key,Description,Enabled,UsagePlanIds; a Key column is required, and a missing Enabled column defaults to true. Duplicate key values are reported in the warnings array, and failonwarnings=true turns those warnings into a BadRequestException.

generateDistinctId

Controls whether the key's id and value fields are distinct. AWS's undocumented default behaviour is that they are the same string unless generateDistinctId=true is explicitly requested.

generateDistinctId id value
absent (default) same as value caller-supplied value, or a generated UUID-derived string
false same as value caller-supplied value, or a generated UUID-derived string
true opaque short token (shortId) caller-supplied value, or a generated UUID-derived string

When generateDistinctId is absent or false, a single shared string is used for both id and value. If the caller supplies a value in the request body, that string is used for both; otherwise a UUID-derived string is generated and assigned to both.

When generateDistinctId=true, id is set to an opaque short token independent of value.

Revocation

DeleteApiKey detaches the key from every usage plan before removing it, matching AWS. A usage plan key stores its own copy of the key value, so without that sweep a deleted key would stay listed by GetUsagePlanKeys and keep being recognised on the data plane.

requestContext.identity.apiKey is only populated when the x-api-key header matches a key that still exists and has enabled set to true, so disabling a key through UpdateApiKey takes effect immediately.

Note

Floci does not implement the apiKeyRequired gate on methods, so a request carrying an unknown, disabled, or deleted key is still executed — it simply arrives with a null identity.apiKey rather than being rejected with 403.

Not Implemented

These management-plane operations have no handler in v1. Calls will return 404 or an error:

  • Authorizer testing: TestInvokeAuthorizer
  • Model templates: GetModelTemplate
  • Gateway Responses (the entire family: PutGatewayResponse, GetGatewayResponse, etc.)
  • Documentation parts and versions (the entire family, 10 operations)
  • VPC Links (5 operations)
  • Client Certificates (5 operations)
  • GetExport / ImportDocumentationParts

The execute plane (actual proxied HTTP traffic via /restapis/{id}/{stage}/_user_request_/…) is implemented separately and is not counted as management-plane operations. It supports AWS_PROXY (Lambda proxy), AWS (Lambda with VTL request/response templates), and MOCK integrations; other integration types return an error.

Examples

export AWS_ENDPOINT_URL=http://localhost:4566

# Create a REST API
API_ID=$(aws apigateway create-rest-api \
  --name "My API" \
  --query id --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Get the root resource
ROOT_ID=$(aws apigateway get-resources \
  --rest-api-id $API_ID \
  --query 'items[?path==`/`].id' --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Create a resource
RESOURCE_ID=$(aws apigateway create-resource \
  --rest-api-id $API_ID \
  --parent-id $ROOT_ID \
  --path-part users \
  --query id --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Add a GET method
aws apigateway put-method \
  --rest-api-id $API_ID \
  --resource-id $RESOURCE_ID \
  --http-method GET \
  --authorization-type NONE \
  --endpoint-url $AWS_ENDPOINT_URL

# Add a Lambda integration
aws apigateway put-integration \
  --rest-api-id $API_ID \
  --resource-id $RESOURCE_ID \
  --http-method GET \
  --type AWS_PROXY \
  --integration-http-method POST \
  --uri "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:my-function/invocations" \
  --endpoint-url $AWS_ENDPOINT_URL

# Deploy to a stage
aws apigateway create-deployment \
  --rest-api-id $API_ID \
  --stage-name dev \
  --endpoint-url $AWS_ENDPOINT_URL

# Call the deployed API
curl http://localhost:4566/restapis/$API_ID/dev/_user_request_/users

Usage Plan Tags and Custom IDs

Usage plans accept arbitrary tags, and the same reserved floci:override-id tag used for custom API IDs pins the plan's id:

# Create a usage plan with a custom ID and additional tags
aws apigateway create-usage-plan \
  --name "my-plan" \
  --tags '{"floci:override-id":"my-plan-id","env":"staging"}' \
  --endpoint-url $AWS_ENDPOINT_URL

# The plan is now accessible at its custom ID
aws apigateway get-usage-plans --endpoint-url $AWS_ENDPOINT_URL

The override key is validated and consumed exactly as it is for CreateRestApi, so it never appears in the tags a usage plan returns. The deprecated _custom_id_ key is still honored on create for existing setups, and floci:override-id wins when both are present. Every other tag is persisted and returned in CreateUsagePlan and GetUsagePlans responses.


Configuration

Variable Default Description
FLOCI_SERVICES_APIGATEWAY_ENABLED true Enable or disable API Gateway v1 (REST APIs)
FLOCI_SERVICES_APIGATEWAYV2_ENABLED true Enable or disable API Gateway v2 (HTTP and WebSocket APIs)

API Gateway v2 (HTTP and WebSocket APIs)

Protocol: REST JSON Endpoint: http://localhost:4566/v2/apis/...

Both HTTP and WebSocket protocol types are fully supported, including the WebSocket data-plane (real connection handling, message routing, and the @connections management API).

HTTP API data-plane

API Gateway v2 advertises HTTP APIs through Floci's local execute-api domain:

curl http://{apiId}.execute-api.localhost.floci.io:4566/{stageName}/{path}

When an API has a $default stage, callers may omit the stage segment:

curl http://{apiId}.execute-api.localhost.floci.io:4566/{path}

APIs created or updated with disableExecuteApiEndpoint reject requests to this default hostname with 404 Not Found, matching AWS HTTP API behavior.

Supported Operations

Category Operations
APIs CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, DeleteCorsConfiguration
Routes CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute
Route Responses CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse
Integrations CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration
Integration Responses CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse
Authorizers CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer
Stages CreateStage, GetStage, GetStages, UpdateStage, DeleteStage
Deployments CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment
Models CreateModel, GetModel, GetModels, UpdateModel, DeleteModel
Domain Names CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName
API Mappings CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping
VPC Links CreateVpcLink, GetVpcLink, GetVpcLinks, DeleteVpcLink
Tags TagResource, UntagResource, GetTags

WebSocket Data-Plane

Floci supports real WebSocket connections for API Gateway v2 WebSocket APIs. Clients connect via:

ws://localhost:4566/ws/{apiId}/{stageName}

Supported Features

Feature Status
$connect route with Lambda integration ✅
$disconnect route with Lambda integration ✅
$default route (fallback) ✅
Custom routes via routeSelectionExpression ✅
Route response selection expression ✅
Lambda REQUEST authorizer on $connect ✅
Identity source validation (header/querystring) ✅
@connections POST (send message to client) ✅
@connections GET (get connection info) ✅
@connections DELETE (disconnect client) ✅
Stage variable substitution in integration URIs ✅
AWS_PROXY integration (Lambda) ✅
AWS integration (Lambda with VTL templates) ✅
HTTP_PROXY integration ✅
HTTP integration (with VTL templates) ✅
MOCK integration ✅
GoneException (410) for disconnected connections ✅
Binary frame support (isBase64Encoded: true) ✅
$connect response headers propagation ✅
128 KB payload size limit enforcement ✅
10-minute idle timeout ✅
2-hour max connection duration ✅

@connections Management API

The @connections API allows server-side code (e.g., Lambda functions) to send messages to connected clients, retrieve connection metadata, or disconnect clients:

POST   /execute-api/{apiId}/{stageName}/@connections/{connectionId}  — Send message
GET    /execute-api/{apiId}/{stageName}/@connections/{connectionId}  — Get connection info
DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId}  — Disconnect client

Behavior Notes

  • Connection URL: Floci accepts the AWS-style execute-api host as well as the path form. All of these reach the same WebSocket API:

    • ws://{apiId}.execute-api.{region}.localhost:4566/{stage} — region-bearing, mirroring AWS's wss://{api-id}.execute-api.{region}.amazonaws.com/{stage}
    • ws://{apiId}.execute-api.localhost.floci.io:4566/{stage} — Floci's built-in execute-api domain (regionless; the region is resolved by an apiId lookup)
    • ws://localhost:4566/ws/{apiId}/{stage} — the explicit path form

    The @connections management API is likewise reachable on the execute-api host (http://{apiId}.execute-api.{region}.localhost:4566/{stage}/@connections/{connectionId}).

  • Idle timeout: 10 minutes (matching AWS default). Not configurable per-API.

  • Max connection duration: 2 hours (matching AWS). Connections are closed automatically.

  • Payload size limit: 128 KB per frame (matching AWS). Oversized messages receive an error frame.

Not Implemented

  • ReimportApi, ExportApi, UpdateDomainName, UpdateApiMapping
  • UpdateVpcLink — the other four VPC Link operations are implemented; see the table above

Examples

export AWS_ENDPOINT_URL=http://localhost:4566

# Create an HTTP API
API_ID=$(aws apigatewayv2 create-api \
  --name "My HTTP API" \
  --protocol-type HTTP \
  --query ApiId --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Create a Lambda integration
INTEGRATION_ID=$(aws apigatewayv2 create-integration \
  --api-id $API_ID \
  --integration-type AWS_PROXY \
  --integration-uri "arn:aws:lambda:us-east-1:000000000000:function:my-function" \
  --payload-format-version 2.0 \
  --query IntegrationId --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Create a route
aws apigatewayv2 create-route \
  --api-id $API_ID \
  --route-key "GET /users" \
  --target "integrations/$INTEGRATION_ID" \
  --endpoint-url $AWS_ENDPOINT_URL

# Deploy
aws apigatewayv2 create-stage \
  --api-id $API_ID \
  --stage-name dev \
  --auto-deploy \
  --endpoint-url $AWS_ENDPOINT_URL

WebSocket API

export AWS_ENDPOINT_URL=http://localhost:4566

# Create a WebSocket API
WS_API_ID=$(aws apigatewayv2 create-api \
  --name "My WebSocket API" \
  --protocol-type WEBSOCKET \
  --route-selection-expression '$request.body.action' \
  --query ApiId --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Create a Lambda integration
WS_INTEGRATION_ID=$(aws apigatewayv2 create-integration \
  --api-id $WS_API_ID \
  --integration-type AWS_PROXY \
  --integration-uri "arn:aws:lambda:us-east-1:000000000000:function:my-ws-handler" \
  --query IntegrationId --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Create $connect, $disconnect, and $default routes
aws apigatewayv2 create-route \
  --api-id $WS_API_ID \
  --route-key '$connect' \
  --target "integrations/$WS_INTEGRATION_ID" \
  --endpoint-url $AWS_ENDPOINT_URL

aws apigatewayv2 create-route \
  --api-id $WS_API_ID \
  --route-key '$disconnect' \
  --target "integrations/$WS_INTEGRATION_ID" \
  --endpoint-url $AWS_ENDPOINT_URL

aws apigatewayv2 create-route \
  --api-id $WS_API_ID \
  --route-key '$default' \
  --route-response-selection-expression '$default' \
  --target "integrations/$WS_INTEGRATION_ID" \
  --endpoint-url $AWS_ENDPOINT_URL

# Deploy
aws apigatewayv2 create-stage \
  --api-id $WS_API_ID \
  --stage-name prod \
  --endpoint-url $AWS_ENDPOINT_URL

# Connect via WebSocket (using wscat or any WebSocket client)
# wscat -c ws://localhost:4566/ws/$WS_API_ID/prod

# Send a message to a connected client via @connections API
# curl -X POST http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID \
#   -d "Hello from server"

# Get connection info
# curl http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID

# Disconnect a client
# curl -X DELETE http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID