Routing

Clink’s routing is simple but efficiency. It not allow parameters in path for explicit and performance. Let use query arguments instead of path parameters. For examples:

Parameter form Argument form
/book/:id /book/item?id=1243
/book/:id/notes /book/item/notes?id=1243
/news/:year/:month/:date /news/archive?year=2017&month=5&date=3

However, arguments isn’t introduce here, it’s introduce in Controller section.

Clink’s routing provides routing methods by three factors: method, path, content-type. All of it can be done with clink.route.

  • clink.route.get(path)
  • clink.route.post(path, type=MIME_JSON)
  • clink.route.put(path, type=MIME_JSON)
  • clink.route.patch(path, type=MIME_JSON)
  • clink.route.delete(path)

As you see, GET and DELETE method ignores content-type because it’s no meaning. Other methods allow content-type with default value is MIME_JSON. You can access shortcut name for MIME type in clink.mime.type.

Example

routing.py
# STEP 1: get clink library
from clink import stamp, mapper, App, AppConf, Controller


# STEP 2: get an WSGI server
from wsgiref.simple_server import make_server


# STEP 3: create application configuration and application
conf = AppConf('book-api', 'Hell Corporation', '1st, Hell street')
app = App(conf)


# STEP 4: define component - controllers
@stamp()
@mapper.path('/book')
class BookCtl(Controller):
    @mapper.get('/item')
    def get_item(self, req, res):
        res.body = {
            'name': 'How to Die',
            'author': 'Death'
        }

# ===[BEGIN] ADD MORE ROUTES HERE ============================================
    @mapper.post('/item', 'text/plain')
    def create_item(self, req, res):
        res.body = {'msg': 'created'}

    @mapper.patch('/item')
    def patch_item(self, req, res):
        res.body = {'msg': 'patched'}

    @mapper.put('/item')
    def put_item(self, req, res):
        res.body = {'msg': 'putted'}

    @mapper.delete('/item')
    def delete_item(self, req, res):
        res.body = {'msg': 'deleted'}
# ===[END] ADD MORE ROUTES HERE ==============================================


# STEP 5: add components to application
app.add_ctl(BookCtl)


# STEP 6: load components
app.load()


# STEP 7: serve application on WSGI server
address = 'localhost'
port = 8080
print('Prepare API on http://%s:%i/book/item' % (address, port))
httpd = make_server(address, port, app)
httpd.serve_forever()

Testing

$ python routing.py &> /dev/null &
[1] 7071

$ curl -X GET localhost:8080/book/item; echo
{"name": "How to Die", "author": "Death"}

$ curl -X POST -H "Content-Type: text/plain" localhost:8080/book/item; \
  echo
{"msg": "created"}

$ curl -X POST -H "Content-Type: application/json" \
  localhost:8080/book/item; echo
{"status_name": "406 Not Accepted", "message": null, "status": 406}

$ curl localhost:8080/not-exist-path; echo
{"status_name": "404 Not Found", "message": null, "status": 404}

$ kill %1