Recently I had to tutor a student on an assignment dealing with the bottle web framework. I had never used the framework before, but it works similar to Flask. It is a nice framework, and I would recommend it for beginners.
I will explore it more in the future to see how it scales in product, but I'm sure the develops over there have tested this.
Let's start with a basic GET request. Bottle create decorators that we can add to our function which will map HTTP requests to the function. We then call Bottle's run function at the end to server our app.
First, we install:
pip install bottle
Now, let's create a file for our app.
touch main.py
Alright, let's begin by importing the bottle framework. Inside of main.py (full file at the end).
import bottle
Next, let's create a hello function and add the @bottle.route
decorator.
@bottle.route('/hello')
def hello():
return "Hello World!"
Notice that we pass a string with our path name /hello
. This tells bottle to
serve our code on this route. For example, a user can navigate (or send a GET request)
to our api with the hello path, i.e. (http://localhost:8080/hello). Then, Bottle
will call our hello function and return the string "Hello World!"
.
Finally, at the end, we need to tell Bottle to run. We do this with the run function.
bottle.run(host='localhost', port=8080, debug=True)
We passed a few parameters here. We specificed the host to be our localhost, the port to be 8080, and we set debug to be True for testing purposed.
Now, we can point our browser to http://localhost:8080/hello
and we will see "Hello World!"
.
Here is the full code.
import bottle
@bottle.route('/hello')
def hello():
return "Hello World!"
bottle.run(host='localhost', port=8080, debug=True)
Alright, so we learned how to do a basic GET request. Let's end by building a simple POST request. The pattern is similar to the above. Here is the code.
@bottle.post('/accept-some-data')
def handle_post():
username = bottle.request.forms.get('username')
return "Thank you, " + username
Here we changed the route
decorator to post
. That allows users
to send a POST request to our api. We also use the bottle.request
data
to graph from data. This can come from an html form or form data from a
curl request.
That's it for now! Bottle looks like a nice micro-framework for building out an api. If you use it in your projects, let me know what you build in the comments below. Check out more on the official website: https://bottlepy.org.