wichert / rest_toolkit

Simple REST servers
http://rest-toolkit.rtfd.org/
BSD 2-Clause "Simplified" License
36 stars 7 forks source link

Common path prefix #13

Open tholo opened 9 years ago

tholo commented 9 years ago

It would be nice if one could configure a default path prefix, e.g. something like "/api/v1" to be used for all resources.

I tried the obvious and used config.include('rest_toolkit', route_prefix='/api/v1'), but that did not do anything...

wichert commented 9 years ago

That doesn't do anything because your resources are not defined in rest_toolkit, but in your code. What you can do is to put your REST API in a separate package in your project. What I do for applications where I have both an API and a separate website is that I create an api package with the (REST) API, and a site package with the other website code. Each package has itsan includeme() function in its __init__.py, which I include from the main entry point. In you case that would look something like this:

# This is your main application code
config.include('mypackage.api', route_prefix='/api/v1')
config.include('mypackage.site')

Make sure you only do a config.scan() call in the includeme() function in the api and site packages, and not in your main application, otherwise you'll still end up registering routes without the prefix. For example for the api package your __init__.py could look something like this:

def includeme(config):
    config.include('rest_toolkit')  # This is not needed by the main application
    config.scan()  # Scan API code
tholo commented 9 years ago

Huh. Never thought of doing it that way (moving the scan() calls down into subpackages, in effect) — that should definitely fix things for me, at least for this particular application.

Thank you!

wichert commented 9 years ago

No problem!

I'll keep this ticket open as a hint for myself to add this trick to the documentation.