Ok so I have my apps, that takes requests from root / Almost everything is using traversal.
But i’d like to make on top of that site a rest api.
So I’m off with two choices. I either separate the that in two different apps and put that rest application to : rest.site.com, Or I can move it to site.com/rest/*traversal
If I’m doing “/rest/*traversal”, I guess I’ll have to add a route called rest_traversal where the traversal path will be *traversal with the route /rest/*traversal. I did that once for an admin page.
I was wondering if there was a cleanest way to do that. I tried to use virtual_root, but as I understand virtual_root is actually getting added to the path for traversal.
like having virtual_root = /cms and requesting /fun will create the following path /cms/fun
I on the other hand wish to have /cms/fun turned into /fun
If you’re using traversal already, why not just use it to return your “rest API root” object when Pyramid traverses to
/rest/? From there, everything will work naturally.If your “application tree” and “API tree” have the same children and you want to have different views registered for them depending on which branch of the tree the child is located in, you can use
containmentview predicate to register your API views, so they will only match when the child is inside the “API branch”:Another approach would be not to build a separate “API tree” but to use your “main” application’s “URI-space” as RESTful API. The only problem with this is that GET and possibly POST request methods are already “taken” on your resources and mapped to your “normal” views which return HTML or consume HTTP form POSTs. There are numerous ways to work around this:
register the API views with a separate name, so, say
GET /users/123would return HTML andGET /users/123/jsonwould return a JSON object. Similarly,POST /users/123would expect HTTP form to be posted andPOST /users/123/jsonwould expect JSON. A nice thing about this approach is that you can easily add, say, an XML serializer atGET /users/123/xml.use custom view predicates so
GET /users/123andGET /users/123?format=jsonare routed to different views. Actually, there’s a built-inrequest_parampredicate for that since Pyramid 1.2use
xhrpredicate to differentiate requests based onHTTP_X_REQUESTED_WITHheader oracceptpredicate to differentiate onHTTP_ACCEPTheader