Setting Up an API

Due to the nature of App Engine, you may or may not be able to build your entire application using the service. However, just because it has certain limitations that make it ill-suited for all aspects of realtime web development, this doesn’t mean you should ditch it all together.

For the sake of discussion, let’s say that we wanted to expand our Twitter application to send instant messages when it encountered certain words as they came through the stream. Perhaps a user could set up the ability to track his own username in realtime. This would be a perfect use of App Engine if it weren’t for the fact that you can’t run the code that connects to Twitter and monitors the updates. The 30-second execution limit would get in the way and make it unsuitable for that part of the application.

However, since we’ve already built the Twitter application using the Tornado framework, there is no need to build it on App Engine. We could simply add some API functionality to this instant message code and then modify the Twitter application to use that API.

To accept the API requests, we need to add a handler when we create the main application object. In the main function of main.py, make the following modifications:

def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/_ah/xmpp/message/chat/', XMPPHandler),
                                          ('/api/send', APISendHandler)
                                          ], 
                                         debug=True)

That just tells App Engine to use the APISendHandler, when it receives a request to /api/send. Above the main function, ...

Get Building the Realtime User Experience now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.