python requests form urlencoded

Python Requests Form Urlencoded

Python requests module is used to make HTTP requests to a server. It provides support for various HTTP request methods like GET, POST, PUT, DELETE, etc.

The form-urlencoded format is used to send data in the HTTP request. It is the default format used by HTML forms when submitting data.

In Python requests, you can send form-urlencoded data using the data parameter of the requests.post() method.


    import requests

    url = 'https://example.com/api/data'
    payload = {'key1': 'value1', 'key2': 'value2'}
    headers = {'content-type': 'application/x-www-form-urlencoded'}

    response = requests.post(url, data=payload, headers=headers)

    print(response.text)
  

In the code above, we have defined a URL endpoint where we want to send the form data. We have also defined the payload as a dictionary object where each key-value pair represents a form field and its value.

The headers parameter defines the content type of the form data being sent. In this case, it is set to 'application/x-www-form-urlencoded'.

The requests.post() method sends a POST request with the form data to the server and returns a response object. We can then access the response text using the response.text attribute.

If you want to send multiple values for a single key, you can pass a list as the value of that key in the payload dictionary.


    import requests

    url = 'https://example.com/api/data'
    payload = {'key1': ['value1', 'value2'], 'key2': 'value3'}
    headers = {'content-type': 'application/x-www-form-urlencoded'}

    response = requests.post(url, data=payload, headers=headers)

    print(response.text)
  

In the code above, we have sent multiple values for the key 'key1' by passing a list as its value in the payload dictionary.