ESP32 HTTP POST with JSON body using ArduinoJson
This example parses a HTTP POST request body using ArduinoJson. I recommend using my HumanESPHTTP library as simple server library based on the ESP-IDF HTTP server.
constexpr size_t JsonParseBufferSize = 2048;
typedef ArduinoJson::StaticJsonDocument JsonParseBuffer;
/**
* This buffer is used to parse /api/configure events
*/
static JsonParseBuffer document;
static const httpd_uri_t configureHandler = {
.uri = "/api/configure",
.method = HTTP_POST,
.handler = [](httpd_req_t *req) {
// Receive POST body data into a new buffer
char* jsonBody = (char*)malloc(req->content_len + 1);
jsonBody[req->content_len] = '\0'; // NUL terminate [just in case]
if(jsonBody == nullptr) {
return SendStatusError(req, "Failed to allocate memory for JSON body");
}
int err = httpd_req_recv(req, jsonBody, req->content_len);
if(err != req->content_len) {
free(jsonBody);
return SendStatusError(req, "Failed to read request body");
}
// Parse the body as JSON
deserializeJson(document, jsonBody, req->content_len);
// TODO: Do something with [document]
// Cleanup
free(jsonBody);
return SendStatusOK(req);
}
};
which uses the following utility functions:
esp_err_t SendStatusError(httpd_req_t *request, const char* description) {
httpd_resp_set_type(request, "application/json");
httpd_resp_send_chunk(request, "{\"status\":\"error\", \"error\": \"", HTTPD_RESP_USE_STRLEN);
// NOTE: We silently assume that description does not have any special characters
httpd_resp_send_chunk(request, description, HTTPD_RESP_USE_STRLEN);
httpd_resp_send_chunk(request, "\"}", HTTPD_RESP_USE_STRLEN);
httpd_resp_send_chunk(request, nullptr, 0); // Finished
return ESP_OK;
}
esp_err_t SendStatusOK(httpd_req_t *request) {
httpd_resp_set_type(request, "application/json");
httpd_resp_sendstr(request, "{\"status\":\"ok\"}");
return ESP_OK;
}