// Why this matters
Serverless APIs for AWS AI services are the quickest way to give an application intelligence without owning a model. Rekognition reads images, Comprehend reads text, Lex holds a conversation and SageMaker hosts whatever custom model you trained. Each has an SDK, but front-end developers want a URL and a JSON contract.
These integrations also tend to be the part of a project with the sharpest cost and security edges: image uploads, user text, and per-request pricing. A thin, well-scoped API layer is where you put the limits, the validation and the logging, and it lets you swap a service later without touching clients.
// The problem
Calling the services directly from a browser means shipping credentials or Cognito identity pools with broad permissions, and exposing the full vendor response. Calling them from one big backend function creates a policy that can read every bucket, call every service and run for the maximum timeout, which is a security review waiting to fail.
Each service also has constraints that bite late. API Gateway rejects large request bodies, so base64 images fail at scale. Comprehend limits document size and batch count. SageMaker real-time endpoints bill continuously whether or not anyone calls them, and cold serverless endpoints add seconds of latency. Lex V2 needs aliases and locale configuration that differ from V1 examples you find online.
The result is a lot of glue code with slightly different error shapes. Without a consistent contract, every new capability becomes another special case for the front end.
// The solution
We build one function per capability and give each only the IAM actions it needs. The Rekognition function can call DetectLabels and read one bucket prefix, nothing else. That separation also makes timeouts and memory sizing honest: the Comprehend function needs 256 MB and ten seconds; a SageMaker invoke function might need more.
Images enter through a presigned upload to S3, which sidesteps the API Gateway payload limit and keeps large bodies off Lambda, the same approach as Presigned-Upload Document Parsing API. The analysis function then receives only a key. For text we validate length and language up front and use the batch operations to cut calls.
SageMaker is the one place with a real cost decision. A real-time endpoint is the right choice for steady traffic. For a voice-cloning or occasional inference workload, a serverless inference configuration or a scheduled scale-to-zero keeps the bill honest, at the cost of a cold start the caller must tolerate. The Lambda stays the same either way because it only knows the endpoint name.
Every function returns the same envelope: a request id, the capability, a result object and a list of warnings. We map vendor fields into that shape, keeping only what clients use. That is the part clients thank you for when you later replace Comprehend with a custom model or add a second language.
- Clientcalls a plain HTTPS route
- API Gatewayauthenticates and throttles
- Validation gate gateLambda checks size, type and required fields
- Router Lambdaone function per AI capability
- Service callSageMaker, Rekognition, Comprehend or Lex runtime
- Normalisemap the vendor response into a small stable shape
- Storeoptionally persist results in DynamoDB or S3
- RespondJSON with request id and confidence values
// Before you start
- AWS account in a region where the target services are available
- AWS SAM CLI or CloudFormation access, and Python 3.12
- A trained model and endpoint in SageMaker if you want the custom inference path
- An S3 bucket for image uploads with a lifecycle rule to expire them
- Lex V2 bot with a published alias and locale, if you need the chatbot route
// Step-by-step implementation
01 Template with one function per capability
Declare a function for each service with its own role. The inline policies are the point: if someone later asks what the image function can touch, the answer is on one screen. A shared HTTP API with a usage plan handles throttling.
Keep the model endpoint name and bot ids as parameters so the same template deploys to staging and production.
02 A shared response envelope and input guard
Put validation and the response shape in one small module that every handler imports. It limits body size, parses JSON safely and wraps results. Doing this once means error handling is consistent and nobody returns a raw stack trace to a client.
03 Analyze images with Rekognition from S3
Rekognition can read the object straight from S3, so the Lambda never downloads the bytes. Restrict the key prefix, set a minimum confidence to drop noise and run moderation labels alongside general labels when the images are user generated.
Return only name and confidence. Clients rarely need the full taxonomy, and trimming keeps responses small.
04 Sentiment with Comprehend, in batches
BatchDetectSentiment takes up to 25 documents per call, each limited in size, and is far cheaper per item than single calls. Truncate each text and chunk the list. Detect or require the language code; passing the wrong one gives confident nonsense.
Return the dominant sentiment with the scores, so a dashboard can chart both.
05 Invoke a SageMaker endpoint from Lambda
The Lambda is a translator: validate input, call
invoke_endpoint, return the result. It only knows the endpoint name. That means you can move from a real-time endpoint to a serverless one, or replace the model, without a client change.Voice and other heavy models can take tens of seconds; set the function timeout accordingly and return an asynchronous job id instead if the work exceeds the API Gateway limit, as in Container-Image Lambdas for Audio Segmentation and Sentiment.
06 Hold a conversation with Lex V2
Lex V2 keeps session state on its side, keyed by a session id you supply. Use a stable id per user conversation and pass it every turn. Return the bot messages and the current intent state so the front end can render quick replies or hand off to a person.
The runtime call needs the bot id, the alias id and the locale. Mixing these up gives a not-found error that looks like a permissions problem.
07 Presigned upload route and a smoke test
The upload route returns a presigned PUT URL scoped to the uploads prefix with a short expiry and a content-type condition. Pair it with a bucket lifecycle rule so test images do not accumulate.
Then a smoke script exercises every route end to end; keep it in the repo and run it after each deploy.
// How to verify it works
- Call /sentiment with two clearly different sentences and confirm POSITIVE and NEGATIVE with scores that sum to roughly 1.
- Upload a known image and call /analyze; confirm sensible labels and an empty flagged list.
- Call /chat twice with the same session id and confirm the second reply reflects conversation state.
- Call /infer with a valid sample and confirm a result; send oversized input and confirm a 400.
- Open the Lambda role for each function in IAM and confirm it lists only its own service actions.
// Design decisions and trade-offs
- Wrap each AI service in its own small Lambda with a narrow IAM policy
- Accept images by S3 key or presigned upload, never as large base64 bodies through API Gateway
- Batch Comprehend calls and truncate text to service limits before sending
- Keep SageMaker endpoints behind an invoke Lambda and scale them to zero with serverless or scheduled capacity
- Return stable, minimal JSON so the front end never depends on raw service responses
// Pitfalls and lessons learned
- Sending base64 images through API Gateway hits the payload limit; use S3 and pass keys.
- Granting
rekognition:*ands3:*on one shared role makes the least-privilege story untenable. - Comprehend returns an ErrorList entry per failed document rather than failing the call; ignoring it drops results silently.
- A real-time SageMaker endpoint left running after a demo is the classic surprise bill.
- Lex V2 examples online often use the V1 API; the runtime client names are different.
- Returning the raw vendor response couples clients to it and leaks fields you did not intend to expose.
- Missing text length and language checks produce confident but meaningless sentiment results.
// Frequently asked questions
How do I call Rekognition from Lambda through API Gateway?
Upload the image to S3 with a presigned URL, send the key to a Lambda behind API Gateway, and call DetectLabels with an S3Object reference. Return a trimmed result.
How do I invoke a SageMaker endpoint from Lambda?
Use the sagemaker-runtime client invoke_endpoint with the endpoint name, content type and body, and give the function the sagemaker:InvokeEndpoint permission on that endpoint only.
Can Comprehend sentiment run on many texts at once?
Yes. BatchDetectSentiment takes up to 25 documents per call; chunk larger lists and check ErrorList in each response.
How do I keep SageMaker costs down for occasional use?
Use serverless inference or scale the endpoint down outside business hours, and accept a cold start on the first request.
What about long-running inference?
Return a job id and process asynchronously, as in Event-driven Call-Recording Transcoding and Transcription, because API Gateway has a short integration timeout.
// The outcome
Each AI capability is an ordinary HTTPS endpoint with its own permissions and cost profile, so front-end teams integrate with JSON rather than with five different SDKs. The same pattern covered voice cloning, image analysis, sentiment and chatbot cases.
// Where to take it next
- Add authentication with Cognito or an API key and a usage plan.
- Persist results in DynamoDB and expose a read route for history.
- Add Bedrock as another capability behind the same envelope.
- Add metrics and alarms, as in Automated IAM Compromise Detection and Credential Revocation for the operations side.