CodeBlanks Logo Icon CodeBlanks

async post

Learn POST requests with await session.post.

async post

session.post(url, data=...) is the asynchronous method that makes a POST request. The data parameter carries a form body; for structured data, use the content parameter.

async with session.post(url, data={"ad": "Ayşe"}) as resp:
    print(await resp.text())

POST is typically used when creating a new resource. The response is opened with async with just like in GET.

Sending form data

Form data is a body of key-value pairs. You pass a dict to the data parameter; aiohttp encodes it automatically as application/x-www-form-urlencoded.

form = {"kullanici": "ayse", "sifre": "gizli"}
async with session.post(url, data=form) as resp:
    print(await resp.text())

For a structured-data body, use the content parameter with an application/json header.

Practice Send form with async post

Start with import asyncio and import aiohttp. Inside async def main() open async with aiohttp.ClientSession() as session:. Make a POST request with async with session.post("https://example.com", data={"ad": "Ayşe"}) as resp:. Print the response with print(await resp.text()). Add asyncio.run(main()).

Starter code

main.py
# load asyncio and aiohttp
# open a session with async with
# make a post request on the session (with data parameter)
# read the response with await and print it
# run main with asyncio.run

Sample solution

main.py
import asyncio
import aiohttp

class _S:
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def post(self, url, **kw): return self
    async def text(self): return 'tamam'

aiohttp.ClientSession = _S

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.post('https://example.com', data={'ad': 'Ayşe'}) as resp:
            print(await resp.text())

asyncio.run(main())

Expected output

tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the data parameter of session.post carry?

  • The response body
  • The form body Correct answer
  • The headers
  • The status code

Explanation: The data parameter carries the request body.

2 Complete the post call

Question
async with ____("https://example.com", data={"ad": "Ayşe"}) as resp:
Answer
async with session.post("https://example.com", data={"ad": "Ayşe"}) as resp:

Explanation: session.post(url, data=...) makes a POST request.

3 Match the post concepts

Term Meaning
session.post Makes a POST request
data Carries form body
content Carries structured data
await resp.text Gives response body

All lessons in Advanced