Skip to content

API Gateway converting UTF-8 characters

0

I suspect this is something I've omitted to configure, but I can't find anything recent - e.g. some past posts reference changing API Resources, which no longer exist on the current platform.

I have an API that has routes to a number of lambda functions, exposed as HTTP functions. When I make a call from a client, sending for example the string "£5,000" in a JSON payload, it arrives in the lambda function as "£5,000". To make matters worse, this sequence is repeated on each call so the next call results in the lambda getting "£5,000" and so on.

I think this is because the "Content-type" needs to be set to "application/json; charset=utf-8" on the method in the gateway but I can't find how to do this. Any help would be very gratefully received.

Thanks,

David

1 Answer
0

The issue you're experiencing with UTF-8 character encoding in API Gateway is likely related to how the API is configured to handle binary media types and content type conversions. Here are a few steps you can take to address this problem:

  1. Configure binary media types: Add "application/json" to the binaryMediaTypes list on your RestApi resource. This tells API Gateway to treat JSON payloads as potentially containing binary data.

  2. Set content handling: For your integration, set the contentHandling property to CONVERT_TO_TEXT. This ensures that API Gateway correctly handles the UTF-8 encoded JSON string.

  3. Lambda function response: Make sure your Lambda function is returning the response in the correct format, including the proper content type header. The response should look like this:

{ "isBase64Encoded": false, "statusCode": 200, "headers": { "Content-Type": "application/json; charset=utf-8" }, "body": JSON.stringify({ your: "response data" }) }

  1. API Gateway method response: Ensure that the Content-Type header is included in the method response of your API.

By implementing these configurations, you should be able to properly handle UTF-8 characters in your JSON payloads without the encoding issues you're currently experiencing. The repeated encoding problem you're seeing (where "£" becomes "£" and then "ã") is typically a sign of multiple incorrect UTF-8 encodings being applied, which these steps should resolve.

If you're still experiencing issues after applying these configurations, you may need to review your client-side code to ensure it's sending the data with the correct encoding as well.
Sources
Content type conversions in API Gateway - Amazon API Gateway
Lambda proxy integrations in API Gateway - Amazon API Gateway
Binary media types for REST APIs in API Gateway - Amazon API Gateway

answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.