ESP32 / ESP8266 MicroPython: HTTP POST Requests

The objective of this post is to explain how to perform HTTP POST requests using MicroPython and the urequests library. This was tested on both the ESP32 and the ESP8266.


Introduction

The objective of this post is to explain how to perform HTTP POST requests using MicroPython and the urequests library. This was tested on both the ESP32 and the ESP8266. The prints shown here are from the tests performed on the ESP8266.

We are going to send the HTTP POST request to a fake online testing REST API. The main website can be seen here. It supports multiple routes and we are going to use the /posts one. Note however that the name of the route to be used doesn’t have anything to do with the POST method we are going to use. In this case, a post corresponds to a dummy object representing a written post of a user in, for example, a website. On the other hand, POST is the HTTP method we are going to use.

Naturally, to follow this tutorial, the device needs to be previously connected to the Internet, so it can send the HTTP request. Please check this previous post on how to connect a device running MicroPython to a WiFi network. If you want to automate the connection after the device boots, check this other post. In my case, my MicroPython setup automatically connects the device to a WiFi network after the booting procedure.

Important: At the time of writing, the version of MicroPython used had urequests included by default. So, we would only need to import it, without performing any additional procedure. Note however that this may change and newer versions of MicroPython may no longer include it by default and require additional configuration procedures.


The code

The first thing we are going to do is importing the urequests module, to access the function needed to perform the HTTP POST request.

import urequests

Then we are going to send the request by calling the post function of the urequests module. This function receives as input the URL where we want to make the HTTP post request. It can also receive additional arguments in the form of a list of key – argument, since as can be seen by the function definition it has a **kw argument defined in the prototype. You can read more about the **kwargs in this very good article.

Since the post function calls the request function in it’s body, we can check that one of the additional arguments that we can pass is the data parameter. This corresponds to the body of our HTTP POST request.

Since this is a simple example to learn how to use the function, we will just send a string of data as body and we will not specify any particular content-type. Naturally, in a real case scenario, we would wan’t to specify a content-type and respect its format on the body of our request.

Note that the URL corresponds to the /posts route of the fake online REST api website mentioned in the introductory section.

response = urequests.post("http://jsonplaceholder.typicode.com/posts", data = "some dummy content")

Note that this function call will return an object of class Response, which we stored in a variable, so we can process the results of the HTTP request later.

Figure 1 shows the result of this same POST request, performed using Postman. As can be seen, we will receive an answer indicating a new resource was created (a post object with ID 101), independently of the content of our request.

If we keep sending requests, the answer will always be the same, since we are dealing with a fake test API. This is why we didn’t bother specifying the content-type or a request body that would make much sense.

If you need help with sending HTTP POST requests with Postman, please consult this video.

POSTMAN post request to jsonplaceholder

Figure 1 – Output of the HTTP POST request using Postman.

Finally, to get the content of the answer to our request in MicroPython, we just need to access the text property of the Response object. Since the answer is of type JSON, we can also retrieve it as a dictionary object with the parsed content using the json function of the Response object, which uses the ujson library in its implementation.

 
print(response.text)
print(response.json())

You can check bellow in figure 2 the result of all the commands shown in this tutorial. As can be seen, we can access both the raw response in a string format or in a parsed JSON object.

ESP32 ESP8266 MicroPython HTTP POST Request

Figure 2 – Result of the HTTP POST request using MicroPython.

 

Related posts

11 thoughts on “ESP32 / ESP8266 MicroPython: HTTP POST Requests”

  1. Thank you for the article on how to use the urequests.post() command. I wanted to highlight a comment you made which is no small detail: “Since this is a simple example to learn how to use the function, we will just send a string of data as body and we will not specify any particular content-type. Naturally, in a real case scenario, we would wan’t to specify a content-type and respect its format on the body of our request.”

    Without specifying a Content-Type, my post was failing. I had almost given up when I re-read your article and did a quick search on Content-Type for this=type&of=request.

    Like ‘data’, urequests also accepts ‘headers{}’ which you will want to use if you are trying to make a real post request. For my example above, both of the following worked:

    {‘Content-Type’: ‘content_type_value’} and {Content-Type’: ‘application/x-www-form-urlencoded’} worked for me. So…

    r=urequests.post(‘http://www.website.com/my_php_that_does_something.php’, data=’this=type&of=data’, headers={‘Content-Type’: ‘content_type_value’})

    I hope this helps someone like your post helped me.

    1. Hi! Thank you very much for the feedback 🙂

      It is indeed fundamental to use the correct format and content-type on a real scenario application, in order for the backend to correctly interpret the request.

      On this tutorial, I did not add it because at the time of writing the fake API testing website would answer anyway, even without any content-type.

      But thank you very much for the detailed explanation of your problem and how you have solved it, it will indeed be very useful for others who may be experiencing the same problem 🙂

      Best regards
      Nuno Santos

  2. Thank you for the article on how to use the urequests.post() command. I wanted to highlight a comment you made which is no small detail: “Since this is a simple example to learn how to use the function, we will just send a string of data as body and we will not specify any particular content-type. Naturally, in a real case scenario, we would wan’t to specify a content-type and respect its format on the body of our request.”
    Without specifying a Content-Type, my post was failing. I had almost given up when I re-read your article and did a quick search on Content-Type for this=type&of=request.
    Like ‘data’, urequests also accepts ‘headers{}’ which you will want to use if you are trying to make a real post request. For my example above, both of the following worked:
    {‘Content-Type’: ‘content_type_value’} and {Content-Type’: ‘application/x-www-form-urlencoded’} worked for me. So…
    r=urequests.post(‘http://www.website.com/my_php_that_does_something.php’, data=’this=type&of=data’, headers={‘Content-Type’: ‘content_type_value’})
    I hope this helps someone like your post helped me.

    1. Hi! Thank you very much for the feedback 🙂
      It is indeed fundamental to use the correct format and content-type on a real scenario application, in order for the backend to correctly interpret the request.
      On this tutorial, I did not add it because at the time of writing the fake API testing website would answer anyway, even without any content-type.
      But thank you very much for the detailed explanation of your problem and how you have solved it, it will indeed be very useful for others who may be experiencing the same problem 🙂
      Best regards
      Nuno Santos

      1. Getting this error from last 2 days:
        trying
        resp = urequests.post(API_ENDPOINT,data=data, headers=HEADERS)
        print(resp.ok)
        Traceback (most recent call last):
        File “”, line 106, in
        File “urequests.py”, line 120, in post
        File “urequests.py”, line 60, in request
        OSError: [Errno 103] ECONNABORTED
        urequests not working in micropython nedd help

  3. Dhielber Manzoli

    This is still helping people! Thanks man! Also thanks to the guy with the ‘headers{}’ comment, it was exactly what was happening to me as well!

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading