Making PUT Requests with aiohttp in Python

Mar 3, 2024 ยท 2 min read

The aiohttp library in Python provides a simple way to make HTTP requests, including PUT requests, asynchronously. PUT requests are used to create or update a resource on the server.

To make a PUT request with aiohttp:

import aiohttp

async with aiohttp.ClientSession() as session:
    async with session.put(url, data=payload) as response:
        print(response.status)

Some key points:

  • The put() method on the ClientSession sends the PUT request
  • We pass in the url to PUT to, and optionally data to include as the request body
  • This returns a ClientResponse object that we use in an async with block to get the response status, text, etc.
  • For example, to update a user profile on a server:

    data = {'name': 'John', 'age': 30}
    async with session.put('https://api.server.com/users/123', json=data) as resp:
        print(resp.status)

    Here we PUT to update user 123, passing the updated data in JSON format.

    Some tips when making PUT requests:

  • Generally PUT is used to create/update a resource, POST is used to send data to be processed
  • Use json= or data= to attach a body. json= will serialize the python dict to JSON
  • Check the status to see if the PUT succeeded or failed
  • PUT can also be useful for operations like:

  • Uploading a file to storage
  • Saving an object to a database
  • Creating resources in a REST API
  • Some challenges with PUT requests:

  • Handling errors and failed requests properly
  • Securing the API endpoint to prevent unauthorized PUTs
  • Ensuring idempotence - that calling PUT multiple times has the same effect
  • In summary, aiohttp provides a convenient way to dispatch PUT requests in async Python. It handles serialization, connections, and more under the hood allowing you to focus on the API logic. Proper use of PUT opens up many possibilities for creating and updating resources.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: