CoAP POST Request Returns 4.00 Bad Request
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about CoAP POST Request Returns 4.00 Bad Request. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
CoAP POST request to create a resource returns 4.00 Bad Request.
Quick Fix
Wrong
res.code = '2.01';
res.end(payload);
// Missing Location-Path option```
Client receives 2.01 Created but no Location-Path. Resource cannot be found.
### Right
```cpp
#include <coap.h>
void post_handler(coap_context_t *ctx, coap_resource_t *res,
coap_session_t *session, coap_pdu_t *request,
coap_binary_t *token, coap_string_t *query,
coap_pdu_t *response) {
size_t size;
const unsigned char *data = coap_get_data(request, &size);
if (size == 0) {
coap_pdu_set_code(response, COAP_RESPONSE_CODE_BAD_REQUEST);
return;
}
char buf[64];
snprintf(buf, sizeof(buf), "{"id":"dev-%lu"}", random());
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CREATED);
coap_set_header_location_path(response, buf);
coap_add_data(response, strlen(buf), (const unsigned char*)buf);
}```
Client receives 2.01 Created with Location-Path: dev-12345
## Prevention
CoAP POST creates a sub-resource (like HTTP POST). Return 2.01 (Created) with Location-Path option pointing to the new resource. Validate payload before creating. POST is NOT idempotent (each call creates a new resource). For idempotent create/replace, use PUT.
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
## FAQ
<details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">### POST vs PUT?</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>POST creates under the URL (server assigns ID). PUT creates/replaces at exact URL (client assigns ID). POST is non-idempotent, PUT is idempotent.</p>
<h3 id="what-is-location-path">What is Location-Path?</h3><p>CoAP option telling client where the new resource is. Similar to HTTP Location header. Path is relative to request URL.</p>
<h3 id="can-201-have-no-payload">Can 2.01 have no payload?</h3><p>Yes. 2.01 can have Location-Path only with no body. Client discovers new resource from the path.</p>
</div></details>
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro