Optional path parameters in url

I’m trying to port an app from CherryPy to sanic - with CherryPy in request URIs, path arguments (/ separated) and query string arguments (?name=value) map analogously to python args and kwargs. It’s possible to then swallow any number of positional args with *args.
How might I implement this with sanic routing? Something like:

/<objectname>/<methodname>/<*args>

Thanks

1 Like

Hi Nick,

Currently, sanic supports the following parameters types.

  1. string
  2. int
  3. number
  4. path
  5. alpha
  6. uuid

For further regex details on what is matched, please look at the REGEX_TYPES attribute of the router.py file.

Following is an example of how to use them.

from sanic import Sanic
from sanic.response import json

app = Sanic(__name__)


@app.route("/<arg1:string>/<arg2:int>/<args:path>")
def handler(request, arg1, arg2, args):
    return json({
        "params": {
            "args": args,
            "arg1": arg1,
            "arg2": arg2,
            "query_string": request.raw_args,
            "match_info": request.match_info
        }
    })


app.run(
    host="0.0.0.0",
    port=8989
)
➜  ~ http http://0.0.0.0:8989/1/1/other/and\?test\=v1\&p\=2
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 144
Content-Type: application/json
Keep-Alive: 5

{
    "params": {
        "arg1": "1",
        "arg2": 1,
        "args": "other/and",
        "match_info": {
            "arg1": "1",
            "arg2": 1,
            "args": "other/and"
        },
        "query_string": {
            "p": "2",
            "test": "v1"
        }
    }
}

This should help you get started. Instead of mapping the variable path into *args, you can map it into a path type and then use the split operator to extract everything you want.

1 Like

Thank you, I’m a total moron for not realising that on my own.