Search code examples
python-3.xpostrequest

cannot use python to send post request with parameters and headers


I am trying to use python to send a post request, here is my code:

import requests
data = {
  'api_key': xxxxx,
  'api_id': xxxxx,
  'parameter1': 12
}
requests.post(url=API_ENDPOINT, data=data)

api_key and api_id are the headers and parameter1 is the pass-in parameter. after I run the code, no error message is given, but the post request didn't work successfully. can you please help me to figure it out? Many Thanks!


Solution

  • try sending the data as json

    import requests
    
    api_key = "My_API_Key_Here"
    api_id = "My_API_ID_Here"
    
    headers = {
        'Content-Type': 'application/json',
        'api_key': api_key,
        'api_id': api_id
    }
    data = {
      'parameter1': 12
    }
    
    response = requests.post(API_ENDPOINT, json=data, headers=headers)
    
    # Check the response
    if response.status_code == 200:
        print('Request was successful')
        print(response.json())  # If the response is in JSON format
    else:
        print('Request failed with status code:', response.status_code)
        print(response.text)  # Print the response content for debugging