ESP32 MicroPython: Getting the query parameters on a Picoweb app

The objective of this post is to explain how to get the query parameters of an HTTP request sent to a Picoweb app. The tests were performed on a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.


Introduction

The objective of this post is to explain how to get the query parameters of an HTTP request sent to a Picoweb app. We will use the parser developed on this previous post to obtain the parameter values in a MicroPython dictionary format.

Please note that in order to keep the code simple, we are assuming that the client always sends the query parameters in the correct format and thus we are not doing any validation. Naturally, in a real use case, we need to take in consideration all the failure scenarios and thus check if the parameters were effectively sent and respect the correct format, before using them.

The tests were performed on a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board. The IDE used was uPyCraft.

 

The code

We will start our code by importing both the picoweb and the network modules, which are needed for creating the HTTP server app and to connect the ESP32 to a WiFi network, respectively.

import picoweb
import network

Next we will declare a query string parsing function, which we will use to get the parameters of the query string in the format of a MicroPython dictionary. The code for this function was explained in detail in the previous post, and thus we will not analyse it here.

Note that I’m including the parsing function code in here for simplicity, but the cleanest way of organizing the code is putting it in a distinct module and import it.

def qs_parse(qs):

  parameters = {}
  ampersandSplit = qs.split("&")

  for element in ampersandSplit:
    equalSplit = element.split("=")
    parameters[equalSplit[0]] = equalSplit[1]

  return parameters

Next we will connect the ESP32 to a WiFi network, using the generic code we have been using in the previous tutorials. Again, this can also be encapsulated in a module, for keeping the main code simpler.

ssid = "yourNetworkName"
password =  "YourNetworkPass"
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

ip = station.ifconfig()

Next we create our app instance and specify the route where we will handle the requests. We will be listening on route “/query“.

 
app = picoweb.WebApp("myApp") 

@app.route("/query") 
def query(req, resp):
   ##route handling code

Remember that as first input of the route handling function, we get an object of class HTTPRequest, which we called req when declaring the parameters. Now, in order to get the query string of requests performed in this route, we simply access the qs attribute of that object.

However, from this attribute we will obtain the full query string without being parsed, which is why we are going to need the previously declared parsing function to obtain the parameters and the values in a more usable format. The output of the function will be a dictionary with keys equal to the URL query parameter names and values equal to corresponding URL query parameter values.

 
queryString = req.qs 
parameters = qs_parse(queryString)

We will assume that we are always going to receive two query parameters, one called param1 and the other called param2. Thus, if we access these keys on our dictionary, we will obtain the corresponding values from the URL query string.

To keep the code short, we will assume that the client will always send these parameters correctly and thus we will not do any validation to confirm if the keys exist in the dictionary.

Naturally, in a real scenario application, we should include this kind of safeguard. You can check here how to obtain all the keys available on a MicroPython dictionary, so we can validate them.

To confirm that everything is working fine, we will just return to the client the values of the parameters that have been sent on the query string. As mentioned, we obtain them simply by accessing the dictionary.

 
yield from picoweb.start_response(resp)
yield from resp.awrite("Parameter 1 value: " + parameters["param1"] + "\n")
yield from resp.awrite("Parameter 2 value: " + parameters["param2"])

Finally, we will call the run method on our app instance, binding it to the IP we obtained when the connection to the WiFi network was established. The final source code, which includes this call, can be seen below.

import picoweb
import network

#### Parsing function
def qs_parse(qs):

  parameters = {}
  ampersandSplit = qs.split("&")

  for element in ampersandSplit:
    equalSplit = element.split("=")
    parameters[equalSplit[0]] = equalSplit[1]

  return parameters

#### WiFi Connection
ssid = "yourNetworkName"
password =  "YourNetworkPass"
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

ip = station.ifconfig()

#### Picoweb app
app = picoweb.WebApp("myApp")

@app.route("/query")
def query(req, resp):
    queryString = req.qs

    parameters = qs_parse(queryString)

    yield from picoweb.start_response(resp)
    yield from resp.awrite("Parameter 1 value: " + parameters["param1"] + "\n")
    yield from resp.awrite("Parameter 2 value: " + parameters["param2"])

app.run(debug=True, host =ip[0])


Testing the code

To test the code, simply upload it to the ESP32 and run the script. Upon executing, our Picoweb app root endpoint will get printed to the console. Just copy that URL to a web browser and append to it the route and the query parameters.

Below at figure 1 there’s an example where I’ve assigned the value 10 to param1 and “abc” to param2. Upon hitting enter on the URL browser address bar, you should get a similar output, which shows the correct value of our parameters being returned.

ESP32 MicroPython Picoweb accessing query string parameters

Figure 1 – Output of the request to the defined route, showing the values for the query parameters sent.

Advertisements
This entry was posted in ESP32 and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s