Jump to content
MrGrj

Building a Rest API with the Bottle Framework

Recommended Posts

  • Active Members

REST APIs have become a common way to establish an interface between web back-ends and front-ends, and between different web services. The simplicity of this kind of interface, and the ubiquitous support of the HTTP and HTTPS protocols across different networks and frameworks, makes it an easy choice when considering interoperability issues.

Bottle is a minimalist Python web framework. It is lightweight, fast, and easy to use, and is well-suited to building RESTful services. A bare-bones comparison made by Andriy Kornatskyy put it among the top three frameworks in terms of response time and throughput (requests per second). In my own tests on the virtual servers available from DigitalOcean, I found that the combination of the uWSGI server stack and Bottle could achieve as low as a 140?s overhead per request.

In this article, I’ll provide a walkthrough of how to build a RESTful API service using Bottle.

toptal-blog-image-1450190826314-830cb5528c9d6c342a95f590e8e99be6.jpg

Installation and Configuration

The Bottle framework achieves its impressive performance in part thanks to its light weight. In fact the entire library is distributed as a one-file module. This means that it does not hold your hand as much as other frameworks, but it is also more flexible and can be adapted to fit into many different tech stacks. Bottle is therefore best suited for projects where performance and customizability are at a premium, and where the time-saving advantages of more heavy-duty frameworks are less of a consideration.

The flexibility of Bottle makes an in-depth description of setting up the platform a bit futile, since it may not reflect your own stack. However, a quick overview of the options, and where to learn more about how to set them up, is appropriate here:

Installation

Installing Bottle is as easy as installing any other Python package. Your options are:

  • Install on your system using the system’s package manager. Debian Jessie (current stable) packages the version 0.12 as python-bottle.
  • Install on your system using the Python Package Index with pip install bottle.
  • Install on a virtual environment (recommended).

To install Bottle on a virtual environment, you’ll need the virtualenv and pip tools. To install them, please refer to the virtualenv and pip documentation, though you probably have them on your system already.

In Bash, create an environment with Python 3:

$ virtualenv -p `which python3` env

Suppressing the -p `which python3` parameter will lead to the installation of the default Python interpreter present on the system – usually Python 2.7. Python 2.7 is supported, but this tutorial assumes Python 3.4.

Now activate the environment and install Bottle:

$ . env/bin/activate
$ pip install bottle

That’s it. Bottle is installed and ready to use. If you’re not familiar with virtualenv or pip, their documentation is top notch. Take a look! They are well worth it.

Server

Bottle complies with Python’s standard Web Server Gateway Interface (WSGI), meaning it can be used with any WSGI-compliant server. This includes uWSGI, Tornado, Gunicorn, Apache, Amazon Beanstalk, Google App Engine, and others.

The correct way to set it up varies slightly with each environment. Bottle exposes an object that conforms to the WSGI interface, and the server must be configured to interact with this object.

To learn more about how to set up your server, refer to the server’s docs, and to Bottle’s docs, here.

Database

Bottle is database-agnostic and doesn’t care where the data is coming from. If you’d like to use a database in your app, the Python Package Index has several interesting options, like SQLAlchemy, PyMongo, MongoEngine, CouchDB and Boto for DynamoDB. You only need the appropriate adapter to get it working with the database of your choice.

Bottle Framework Basics

Now, let’s see how to make a basic app in Bottle. For code examples, I will assume Python >= 3.4. However, most of what I’ll write here will work on Python 2.7 as well.

A basic app in Bottle looks like this:

import bottle

app = application = bottle.default_app()

if __name__ == '__main__':
bottle.run(host = '127.0.0.1', port = 8000)

When I say basic, I mean this program doesn’t even “Hello World” you. (When was the last time you accessed a REST interface that answered “Hello World?”) All HTTP requests to 127.0.0.1:8000 will recieve a 404 Not Found response status.

Apps in Bottle

Bottle may have several instances of apps created, but for the sake of convenience the first instance is created for you; that’s the default app. Bottle keeps these instances in a stack internal to the module. Whenever you do something with Bottle (such as running the app or attaching a route) and don’t specify which app you’re talking about, it refers to the default app. In fact, the app = application = bottle.default_app() line doesn’t even need to exist in this basic app, but it is there so that we can easily invoke the default app with Gunicorn, uWSGI or some generic WSGI server.

The possibility of multiple apps may seem confusing at first, but they add flexibility to Bottle. For different modules of your application, you might create specialized Bottle apps by instantiating other Bottle classes and setting them up with different configurations as needed. These different apps could be accessed by different URLs, through Bottle’s URL router. We won’t delve into that in this tutorial, but you are encouraged to take a took at Bottle’s documentation here and here.

Server Invocation

The last line of the script runs Bottle using the indicated server. If no server is indicated, as is the case here, the default server is Python’s built-in WSGI reference server, which is only suitable for development purposes. A different server can be used like this:

bottle.run(server='gunicorn', host = '127.0.0.1', port = 8000)

This is syntactic sugar that let’s you start the app by running this script. For example, if this file is named main.py, you can simply run python main.py to start the app. Bottle carries quite an extensive list of server adapters that can be used this way.

Some WSGI servers don’t have Bottle adapters. These can be started with the server’s own run commands. On uWSGI, for instance, all you’d have to do would be to call uwsgi like this:

$ uwsgi --http :8000 --wsgi-file main.py

Daca sunteti interesati, continuarea este aici

Link to comment
Share on other sites

Interesant. Mai ales partea asta:

"One common reason to build a REST API is to communicate with a JavaScript front-end through AJAX. For some applications, these requests should be allowed to come from any domain, not just your API’s home domain. By default, most browsers disallow this behavior, so let me show you how to set up cross-origin resource sharing (CORS) in Bottle to allow this:

"

REST si CORS sunt, aparent, ca soaricele si pisica. Daca testezi 10 site-uri cu REST, inclusiv gov sau mil, in 8 din ele CORS este configurat aiurea si poti avea niste surprize majore.

Anyway, merci pentru articol.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...