Getting started¶
Installation¶
Warning
Rafter works with python 3.5 or higher.
Install Rafter with pip (in a virtualenv or not):
pip install rafter
If you’d like to test and tamper the examples, clone and install the project:
git clone https://github.com/olivier-m/rafter.git
pip install -e ./rafter
First basic application¶
Our first application is super simple and only illustrates the ability to directly return arbitrary data as a response, and raise errors.
# -*- coding: utf-8 -*-
from rafter import Rafter, ApiError, Response
# Our main Rafter App
app = Rafter()
@app.resource('/')
async def main_view(request):
# Simply return arbitrary data and the response filter
# will convert it to a sanic.response.json response.
return {
'data': 'Hello there!'
}
@app.resource('/p/<param>')
async def with_params(request, param):
# Just return the request's param in a list.
return [param]
@app.resource('/status')
async def status(request):
# Return a 201 response with some data
return Response({'test': 'abc'}, 201)
@app.resource('/error')
async def error_response(request):
# Return an error response with a status code and some extra data.
raise ApiError('Something bad happened!', 501,
extra_data=':(')
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000)
Tip
If you cloned the repository, you’ll find the examples in the rafter/examples
folder.
The next given command will take place in your rafter
directory.
Launch this simple app with:
python examples/simple.py
Now, in another terminal, let’s call the API:
curl http://127.0.0.1:5000/
You’ll receive a response:
{"data":"Hello there!"}
Then you can try the following API endpoints and see what it returns:
curl http://127.0.0.1:5000/p/test-param
curl -v http://127.0.0.1:5000/status
curl -v http://127.0.0.1:5000/error
Tip
To ease your tests, I strongly advise you to use a full-featured HTTP client. Give Insomnia a try; it’s a very good client with many options.
Now, let’s see in the next part what we can do with routing and responses.