Lambda调用HTTP端点返回422错误,CloudWatch日志显示无法处理求助
Hey there! That 422 Unprocessable Entity error is super common when sending JSON from Lambda to an HTTP endpoint—let’s walk through the most likely reasons and fixes:
Missing or Wrong
Content-TypeHeader
Most APIs explicitly require theContent-Type: application/jsonheader to recognize the payload as JSON. If your Lambda request skips this, the server won’t know how to parse your data, leading to a 422.
For example, in Python:# ❌ Wrong: Uses data= which sends form-encoded data response = requests.post(YOUR_URL, data={"username": "johndoe"}) # ✅ Correct: Uses json= which auto-adds Content-Type header response = requests.post(YOUR_URL, json={"username": "johndoe"}) # Or manually set headers if using json.dumps() import json headers = {"Content-Type": "application/json"} payload = json.dumps({"username": "johndoe"}) response = requests.post(YOUR_URL, data=payload, headers=headers)Invalid JSON Syntax
JSON has strict rules—double quotes only for keys/strings, no trailing commas, and proper nesting. A tiny mistake like using single quotes ({'name': 'Alice'}instead of{"name": "Alice"}) will break parsing. Always use a JSON serializer likejson.dumps()in your code to avoid manual syntax errors.Payload Doesn’t Match API’s Expected Schema
The server might be looking for specific fields that you’re missing, or sending fields with the wrong data type. For example:- If the API expects a
user_id(integer) but you send a string like"123" - If you misspell a required field (e.g.,
emailvs.e-mail)
Double-check the API’s documentation to match your payload structure exactly.
- If the API expects a
URL or Payload Encoding Issues
If you’re manually building URLs or including special characters in your JSON, improper encoding can confuse the server. Using library methods (likerequests’jsonparameter) handles encoding automatically, so stick to those instead of manual string manipulation.VPC/Network Configuration (Less Likely)
If your Lambda is in a VPC, ensure it has outbound internet access via a NAT gateway or VPC endpoint. While this usually causes timeouts or 403s, it’s worth ruling out if all other checks pass.
Quick Debug Tip
Add logging to your Lambda to print the exact request headers and payload being sent. Then replicate that request in tools like Postman or curl—if you get the same 422, you’ll know the issue is with the request itself, not Lambda’s execution.
内容的提问来源于stack exchange,提问作者Weekend Warrior

