2

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.

Will Curran
  • 6,959
  • 15
  • 59
  • 92
  • 1
    `/api/spam` and `/api/spam/{id}` urls refer to *different* resources: a collection and some item in the collection; why should they use the same handler? – jfs Apr 30 '11 at 10:11

1 Answers1

2

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.

Nick Johnson
  • 100,655
  • 16
  • 128
  • 198
  • I never considered them different resources. Isn't spam the same resource whether I'm getting a spam, posting a spam or putting updates to a spam? – Will Curran Apr 30 '11 at 17:31
  • OK I just reread the wikipedia entry and specifically this example: http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services . I understand why a collection and element are different resources, the and I intended both of my uri examples above to represent an element, not a spam collection. So I guess where I am confused is - how do you POST a new element to a uri that expects a key/id? – Will Curran Apr 30 '11 at 17:43
  • @Arch Stanton: If you know resource's url then you could use PUT method to create/replace resource. – jfs Apr 30 '11 at 17:50
  • 1
    Oh wait, it just hit me. I POST a new element to the collection Resource, and I GET/PUT/DELETE an existing element from the element resource. So yes, they are two distinct resources. – Will Curran Apr 30 '11 at 18:11