Python
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.
Exercise 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()).
Show example solution
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())
Test yourself
-
What does the data parameter of session.post carry?
- The response body
- The form body
- The headers
- The status code
Show answer
The form body — The data parameter carries the request body.
-
Complete the post call
async with ____("https://example.com", data={"ad": "Ayşe"}) as resp:
Show answer
async with session.post("https://example.com", data={"ad": "Ayşe"}) as resp:
-
Match the post concepts
- session.post
- Makes a POST request
- data
- Carries form body
- content
- Carries structured data
- await resp.text
- Gives response body
Next lesson: JSON response