Greetings fellow programmers!
My plan is to make an ESP32 client send a dummy POST JSON file to a Python server.
The problem is, I'm not sure how it should be done.
I can make a client in Python, a server and then host that server, send some dummy JSON and print it out in my server terminal.
That's not what I want; I need the client to be my ESP32.
Currently, this is my test client (in Python, which is not what I want):
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print(res.json())
And this is my basic server:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print(content)
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
How should an ESP32 client look like?
So far I've put together the following code:
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <WiFiMulti.h>
const char *AP_SSID = "myssid"; // hidden :)
const char *AP_PWD = "mypassword";
WiFiMulti wifiMulti;
void setup() {
Serial.begin(115200);
delay(2000);
wifiMulti.addAP(AP_SSID, AP_PWD);
postDataToServer();
}
void loop() {
// Not used
}
void postDataToServer() {
Serial.println("Posting JSON data to server...");
if (wifiMulti.run() == WL_CONNECTED) {
HTTPClient http;
http.begin("http://localhost:5000");
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<200> doc;
doc["sensor"] = "gps";
doc["time"] = 135108241220;
String requestBody;
serializeJson(doc, requestBody);
int httpResponseCode = http.POST(requestBody);
if(httpResponseCode>0){
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
}
else {
Serial.println("Error occurred while sending HTTP POST.");
}
}
}
... but this doesn't work.
Any help would be appreciated.