Azure function is not reading my http post body using python

Guillermo Amorin 0 Reputation points
2024-10-28T17:50:43.2233333+00:00

I have an azure function that has this code:

async def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        req_body = req.get_json()
        endpoint = req.url.split('/')[-1]
        if req.method == 'GET' and endpoint == GET_FACETS_PATH:
            return await handle_get_facets()
        elif req.method == 'POST' and endpoint == POST_CHAT_PATH:
            return await handle_post_chat(req_body)
        else:
            return func.HttpResponse(status_code=405)
    except ValueError as e:
        logging.error(f"Error parsing JSON: {str(e)}")
        return func.HttpResponse(status_code=405)

When I send a post with this code:

functionKey = #A KEY FROM AZURE PORTAL
headers_to_send = {
    'x-functions-key': functionKey
}
payload = {'threadId': 13,
           'question': 'hellomessage',
           'field3': 'auto',
             'userId': 206040,
           'userName': 'gatoPaco'}
 
print(payload)
response: requests.Response = requests.post(url, headers=headers_to_send, json=payload)

I have the following error: [Error] Error parsing JSON: HTTP request does not contain valid JSON data

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,073 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. LeelaRajeshSayana-MSFT 15,806 Reputation points Microsoft Employee
    2024-10-31T21:19:12.1266667+00:00

    Hi @Guillermo Amorin Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.

    I have tested this with Python Version 3.11 and function app runtime version 4.1036.2.2. I could pass the payload without any issues and can parse it through the function app. That being said, there are couple of changes you can make in the code and see if that produces the expected results.

    I request you to pass in the Content-Type as application/json through the headers and see if that makes any difference. Although Python app works with single-quotes for strings, if you try to validate the data using a JSON validator, it would fail as it expects double-quotes. Please try the payload in the following format and see if that helps

    headers = {"Content-Type": "application/json", "x-functions-key": functionKey}
    
    # Create a payload for the POST request
    payload = {
        "threadId": 13,
        "question": "hellomessage",
        "field3": "auto",
        "userId": 206040,
        "userName": "gatoPaco"
    }
    
    # Make the POST request
    response = requests.post(url, json=payload, headers=headers)
    
    # Print the response from the server
    print("Status Code:", response.status_code)
    print("Response Body:", response.text)
    
    
    

    If you make any changes to the Azure function through portal editing, you may need to restart the function app to reflect the changes.

    If you keep seeing the issue despite making the above changes, please share more details on the Python version, function app runtime version, function app name for additional investigation.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.