Http Request methods - Python requests

Http Request methods - Python requests

The requests library in Python is a popular tool for making HTTP requests. The library provides functions that correspond to the standard set of HTTP methods. Here's a summary of the most commonly used HTTP request methods and how to use them with the requests library:

  1. GET:

    • Retrieves data from a specified resource.
    • Example:
      import requests response = requests.get('https://api.example.com/data') print(response.text) 
  2. POST:

    • Sends data to a server to create a resource.
    • Example:
      import requests payload = {'key1': 'value1', 'key2': 'value2'} response = requests.post('https://api.example.com/data', data=payload) print(response.text) 
  3. PUT:

    • Updates a current resource or creates a new resource if it does not exist.
    • Example:
      import requests payload = {'key1': 'updated_value'} response = requests.put('https://api.example.com/data/1', data=payload) print(response.text) 
  4. DELETE:

    • Deletes a specified resource.
    • Example:
      import requests response = requests.delete('https://api.example.com/data/1') print(response.status_code) 
  5. HEAD:

    • Retrieves the headers of a resource.
    • Example:
      import requests response = requests.head('https://api.example.com/data') print(response.headers) 
  6. OPTIONS:

    • Returns the HTTP methods that the server supports for a specified URL.
    • Example:
      import requests response = requests.options('https://api.example.com/data') print(response.headers['allow']) # This typically shows the allowed methods. 
  7. PATCH:

    • Applies partial modifications to a resource.
    • Example:
      import requests payload = {'key1': 'partially_updated_value'} response = requests.patch('https://api.example.com/data/1', data=payload) print(response.text) 

When making requests with the requests library, you'll typically want to check the response's status code, headers, and content. You can access these respectively with response.status_code, response.headers, and response.text or response.json() (if the response body contains JSON data).


More Tags

horizontalscrollview pagination xcode4.5 sql-job language-agnostic systemctl reveal.js orchardcms pdf.js marker

More Programming Guides

Other Guides

More Programming Examples