Skip to content

Django on AWS Lambda: HTTP 503 error only when Accept header is text/html, works fine with application/json

0

I'm currently deploying a Django app to AWS Lambda with API Gateway. When I call the API from a browser with the Accept header set to text/html, I get an HTTP 503 response. However, when the Accept header is set to application/json, the API works fine and returns HTTP 200.

I've verified that:

The Lambda function runs correctly and logs are shown as expected. The API Gateway logs show a 503 error. What's confusing is that this issue started after I updated one of the Lambda functions, but another Lambda function that I haven’t updated is also showing the same issue. Has anyone experienced this before? What could be the cause or what should I check next? Could this be due to a change in AWS API Gateway behavior? I need to display the api response and visit the Django admin.

Thanks!

asked a year ago283 views

2 Answers
0

Hello Hank,

I encountered similar behaviour on certain occasions in the past. The fact that it works with Accept: application/json but fails with Accept: text/html suggests the issue is probably related to how Django generates HTML responses and how API Gateway processes them.

For me it was always boiling down to following:

  1. Response Size Limits

In general, HTML responses are usually larger than JSON responses.

I would first do following:

  • Compare the size of your HTML responses vs JSON responses
  • Look for any large static assets being inline in HTML
  • Check if Django Debug Toolbar or similar is adding significant content
  1. Binary Media Types Configuration

Is your API Gateway configured the right way to handle binary content types. HTML responses might contain characters that need binary encoding. If this is the case, in your API Gateway settings, add these binary media types:

  • text/html
  • */*(as a fallback)
  1. Lambda Response Format

Ensure your Lambda function returns responses in the correct format for API Gateway.

Hope it helps

Best regards, Neven

AWS

answered a year ago

  • Thank you so much for your detailed response! Your suggestions are really helpful and I appreciate you sharing your experience.

    1. Regarding Response Size Limits, I've tested this with Django admin and even the simplest /health API, and they're all returning 503 errors. Since these are very minimal responses, it seems like the size might not be the root cause in this case.
    2. For Binary Media Types Configuration, I should have mentioned earlier that I'm using HTTP API (not REST API), so I don't see the Binary Media Types configuration options in my setup.

    Do you have any other ideas about what might be causing this issue? I'm particularly puzzled because it affects both updated and non-updated Lambda functions. Any additional troubleshooting steps you'd recommend would be greatly appreciated!

  • Hello Hank,

    thank you for additional clarification. Since this is happening only with "text/html" content type, the problem is highly likely with the encoding of the response. Few additional stuff which one could check/try:

    1. HTTP API encoding auto-detection In order to "circumvent" response encoding auto-detection, one could try and be more explicit about it:
    def handler(event, context):
        # Your Django processing...
        # Force specific handling for HTML responses
        if 'text/html' in event.get('headers', {}).get('accept', ''):
            html_response = <your_django_response>
            
            # IMPORTANT: Ensure the HTML is a proper string
            if isinstance(html_response, bytes):
                html_response = html_response.decode('utf-8')
            
            return {
                'statusCode': 200,
                'headers': {
                    'Content-Type': 'text/html; charset=utf-8',
                    # Add this header to prevent auto-detection
                    'X-Content-Type-Options': 'nosniff',
                },
                'body': html_response,
                'isBase64Encoded': False  # Explicitly set to False
            }
    
    1. Ensure that Django is consistently handling responses for both JSON and HTML
    2. You could try to force everything through Base64 encoding with following code snippet:
    encoded_body = base64.b64encode(
        html_content.encode('utf-8')
    ).decode('ascii')
    

    Best regards, Neven

  • Thank you very much for providing the solution.

    1. Because my program is wrapped with the Mangum package, the code is as follows. After consulting GPT, I was unable to resolve the issue:
    from mangum import Mangum
    from django.core.asgi import get_asgi_application
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PortalDRFServer.settings")
    
    application = get_asgi_application()
    handler = Mangum(application, lifespan="off")
    
    1. I printed log messages to check, and I believe it's handling both HTML and JSON:
    # Test if BrowsableAPIRenderer works properly
    if "text/html" in request.META.get("HTTP_ACCEPT", ""):
        renderer = BrowsableAPIRenderer()
        # Attempt to initialize renderer
        logging.info("Attempting to use BrowsableAPIRenderer")
    
        # Check template system
        from django.template.loader import get_template
    
        try:
            template = get_template("rest_framework/api.html")
            logging.info("Template loaded successfully")
        except Exception as e:
            logging.error(f"Load fail: {format_exc()}")
    
    logging.info(f"[HealthCheckView.GET] Server is healthy")
    logging.info(f"Request Accept: {request.META.get('HTTP_ACCEPT')}")
    logging.info(f"DEBUG: {settings.DEBUG}")
    logging.info(f"Renderers: {api_settings.DEFAULT_RENDERER_CLASSES}")
    
    # output log
    Attempting to use BrowsableAPIRenderer
    Template loaded successfully
    [HealthCheckView.GET] Server is healthy
    Request Accept: text/html
    DEBUG: True
    Renderers: [<class 'rest_framework.renderers.JSONRenderer'>, <class 'rest_framework.renderers.BrowsableAPIRenderer'>]
    
    1. Sorry, I'm not quite sure how to test this, so I haven't conducted any tests.

    Thank you once again for your assistance. I really appreciate it.

0

This issue where API Gateway returns a 503 error when the Accept header is set to text/html but works fine with application/json could be related to content type handling in API Gateway.

Here are some potential causes and solutions to investigate:

  1. Content Type Configuration: API Gateway might be configured to handle application/json correctly but not text/html. Check if you have any specific content type mappings or transformations in your API Gateway settings.

  2. Binary Content Handling: If your Django application is returning HTML content, API Gateway might need to be configured to handle binary content types. In the API Gateway console, check your API's settings and ensure that "text/html" is added to the binary media types list if you're expecting HTML responses.

  3. Response Transformation: Your Lambda function might be returning responses in a format that API Gateway can process correctly for JSON but not for HTML. Ensure your Lambda function is properly formatting responses for both content types.

  4. CORS Configuration: If this is a cross-origin request issue, verify that your CORS settings in API Gateway include the appropriate headers for both content types.

  5. Lambda Proxy Integration: If you're using Lambda proxy integration, make sure your Lambda function is returning the proper structure with statusCode, headers, and body fields. The headers should include the correct Content-Type based on what was requested.

  6. Headers Configuration: Check if you've added specific headers in the Method request or Method response options in API Gateway. Sometimes adding specific content types in these settings can cause unexpected behavior.

To troubleshoot:

  1. Check CloudWatch logs for both Lambda and API Gateway to see if there are any specific error messages.

  2. Test your API directly from the API Gateway console to isolate if the issue is with the Gateway or your client application.

  3. Try simplifying your response to a basic HTML response to see if that works.

  4. Verify that your Lambda function is correctly handling different Accept headers and responding appropriately.

Since the issue started after updating one Lambda function but affects others as well, it's possible that there was a change in a shared configuration or dependency that impacts how content types are handled across your API Gateway setup.
Sources
API Gateway calls returning HTML, direct calls returning JSON | AWS re:Post
API gateway runs into preflight issue forever after adding a specific Content-Type | AWS re:Post
Api gatway with Lambda function | AWS re:Post
How Does API Gateway Handle the Response Returned by a Lambda Function? | AWS re:Post

answered a year 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.