I want API support for:
GET /api/spam/{id}
POST /api/spam
body: {'name': 'green spam'}
I would normally route to a Handler by:
webapp.WSGIApplication([r'/api/spam/(.*)', APISpam])
class APISpam(RequestHandler):
def get(self, id):
# do stuff
def post(self):
# do stuff
But the post fails because it's expecting a second argument. What is the best design pattern to accommodate RESTful url patterns to Handlers for each type of resource?
UPDATE:
It is being pointed out that the uri examples above represent a collection (/spam) and an element (/spam/{id}). That is not my intention. Both uri examples are for the element spam, one is to GET a specific spam, and the other is to POST a new spam. The reason I am not using /spam/{id} for the POST is because I am creating a new spam, and therefore do not have an id.
Normally you'd simply make them separate handlers: As Sebastian points out, they're different resources - the collection itself, vs one element of the collection.
If you must use the same handler, though, you can supply a default argument:
class APISpam(RequestHandler):
def get(self, id=None):
# do stuff
def post(self, id=None):
# do stuff
application = webapp.WSGIApplication([r'/api/spam(?:/(.*))?'])
Both get and post handlers will be callable without an ID, though - in all likelihood, you really should use separate handlers.