aiocoap

raw JSON →
0.4.17 verified Mon Apr 27 auth: no python

aiocoap is a Python library for the Constrained Application Protocol (CoAP) as defined in RFC 7252. Current version 0.4.17 supports Python >=3.10. It provides both client and server abstractions with async/await support. Releases are semi-regular, with major version changes introducing breaking API shifts.

pip install aiocoap
error ImportError: cannot import name 'Message' from 'aiocoap'
cause Old import path from aiocoap.message import Message used in code written for aiocoap <0.4.
fix
Change to 'from aiocoap import Message'.
error aiocoap.error.FeatureNotImplementedError: DTLS support requires module 'tinydtls'
cause Trying to use coaps:// URIs without installing DTLS support.
fix
Install aiocoap with DTLS extras: pip install aiocoap[dtls] or install tinydtls manually.
error AttributeError: 'EventLoop' object has no attribute 'run_until_complete'
cause Using deprecated loop-based pattern in Python 3.10+ where asyncio.get_event_loop() may return a different loop type.
fix
Use asyncio.run(main()) or Context.create_client_context() as async context manager.
breaking aiocoap 0.4 introduced major API changes: import paths moved from submodules to top-level (e.g., from aiocoap import Message instead of aiocoap.message.Message). Context creation changed: use Context.create_client_context() instead of old patterns asyncio.get_event_loop(). Code written for 0.3.x will not work.
fix Update imports to use top-level names and use the new Context API.
deprecated The async context manager pattern (async with Context.create_client_context()) is now preferred over the old loop-based pattern. Old code using loop.run_until_complete may still work but is deprecated.
fix Use 'async with Context.create_client_context() as context:' to ensure proper resource cleanup.
gotcha CoAP URIs must start with 'coap://' or 'coaps://' (for DTLS). Using 'http://' will cause a silent malformed URI error.
fix Always verify the URI scheme is correct for CoAP.
gotcha When sending large payloads (> 64 KiB), aiocoap requires block-wise transfer (Block1/Block2). Without explicit block options, the library may fail with a MessageTooLong error.
fix Use 'from aiocoap import BlockOption' and set appropriate block options on the request.

Minimal CoAP client that fetches the resource discovery from coap.me.

import asyncio
from aiocoap import *

async def main():
    context = await Context.create_client_context()
    request = Message(code=GET, uri='coap://coap.me/.well-known/core')
    response = await context.request(request).response
    print(response.payload.decode())

if __name__ == "__main__":
    asyncio.run(main())