Parsing HTTP Params in Python Heroku Starter App
A lot of stories I write here (if not all of them) are a result of me spending what I felt was WAY too much time to find a solution to what seems like a simple problem. This was one of those times.
I was working on a project where I was to build a server that responded to simple GET API requests. Heroku was a suggested solution, and since I was able to get the Starter Project up and running, I felt good.
Next, was time to modify the code and take in a parameter, the format being
curl -s https://url.com?var=value
This is where I slipped into the Stack Overflow rabbit hole. I saw plenty of ways to send a GET request in your code (not what I was looking for) and ways to parse a request NOT in url format (unfortunately, my hands were tied with command formatting).
Eventually, however I figured it out by looking closer at the Starter project and, with a little bit of luck, I found what is a very simple way to adapt the Starter project to take in a parameter.
By default, your URL generated with heroku create
will display a basic landing page. Let’s delete that. In hello/views.py, comment out the line of code return render(request, “index.html”)
in the def index(request):
function. Then, if you uncomment return HttpResponse(‘Hello from Python!’)
and push your changes to heroku main, you’ll see the ‘Hello from Python’ string when you go to the URL.
So we know how to send an HttpResponse, but now let’s parse the http request. I started this project for a smart Tic Tac Toe Server, so what I want to do is take in a string representation of X’s, O’s, and +(blank spaces) of a game board state. So from now on I’m going to test my url by adding a parameter, e.g. https://<myserver>.herokuapp.com/?board=xoxox+++x . Note, if you simply go to the url with a parameter, it doesn’t affect the returned response.
Now to parse the url parameter. You can get the parameters of the Http Request with the following:
board = request.GET.get('board')
And then manipulate the variable board as a string:
from django.http import HttpResponse, HttpResponseBadRequest...if board is None: return HttpResponseBadRequest("no board parameter received")if len(board)!=9: return HttpResponseBadRequest("incorrect number of spaces")#TO-DO: game logicreturn HttpResponse(board)
Now if you go to the link or curl -s <URL>
with no parameter, an HttpResponseBadRequest message will be displayed (whatever you use as input to HttpResponseBadRequest()). Similarly, if the board parameter is the wrong number of characters, Bad Request is sent. Otherwise, the “game” proceeds and a board is returned.
Happy Coding!
Colleen