Facebook Apps with Google App Engine

The internet’s simplest introduction to writing a facebook application with Google App Engine, in Python, with Django.

So let’s start with an easy introduction to writing a facebook app with app engine. First of all, you need to sign up for an application with Facebook. You can do this here, just click “set up new application” once you’ve added the facebook developer application, and give them your preferences. You should then come to a page full of settings, with titles like “Essential Information”, and “Basic Information”. Use the navigation on the left to edit the “canvas” settings. Keep this page open.

Now you must sign up for a new application with Google App Engine. That can be done here. Next, you need to write your standard app.yaml file (To illustrate the process, I’m going to be making a simple counter, to count how many times an application “canvas” is viewed). I’m going to call my application “fbstcntr” (as in “facebook stat counter”) The app.yaml file is going to look like this (the stylesheets director is for you to use later when designing your canvas):

application: fbstcntr
version: 1
runtime: python
api_version: 1
handlers:
- url: /stylesheets
static_dir: stylesheets
- url: /.*
script: main.py

Now go back to the facebook settings page, and where it says “Canvas Callback URL”, enter http://(your-application-name).appspot.com. Also, enter the name of your application in “Canvas Page URL”.

Next, you’ll need to make your canvas.html file (this is the one that facebook will use for your application’s canvas). Mine just looks like this (remember I’m using Django, but that’s by no means essential for this tutorial):

<html>
<body>
{{ stat }}
</body>
</html>

Save this file in the same folder as your app.yaml file (the folder I’m using is just called “fb”). Next, we’ll make our main.py file – this is where things get slightly more complicated, but I’ll keep it simple yo.

import cgi
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
# this is a file we'll make next
import facebook
# just a little datastore model
class Stat (db.Model):
visit = db.IntegerProperty(default = 0)
class Canvas(webapp.RequestHandler):
def get(self):
#these are found in facebook's 'My Applications' page
_FbApiKey = 'your api key'
_FbSecret  = 'your secret key'
# Add an element to your datastore
visit = Stat()
visit.put()
# find out how many elements there are in the datastore
query = db.GqlQuery("SELECT __key__ FROM Stat")
results = query.fetch(1000)
stat = str(len(results))
# put this value in your template values
template_values = {"stat": stat}
path = os.path.join(os.path.dirname(__file__), 'canvas.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/', Canvas)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()

Save this file as “main.py”. Next, visit this page, and save all of that code straight into a file called “facebook.py”, and make sure that file is in the same folder as the rest of your application. Well done! You’ve just made the skeleton of your facebook application! Now, run your command prompt, and make it go to where your application is stored (its directory). For me it looks like this:

D:\Graeme\Work and Fun\Python\GAE\fb:

Type in “appcfg.py update ” and the name of the file that is holding your application files. Fire this off and it will update your application!

Every time you visit this application’s page at apps.facebook.com/your-app-name/, it will update the datastore and display the amount of visitors that have been there previously. You can grow this application more by working on your canvas.html file, and including more functions that are available with facebook.py. There are so many possibilities still for facebook apps, and now you can make them and host them for free off Google’s servers – so best of luck!

Enjoy this post? Please share the love...

27 thoughts on “Facebook Apps with Google App Engine

    • thnx for the link……
      Counter app is working nice….
      How can i add facebook login using above facebook.py ……..
      thnx in advance

    • Facebook login? hmmmm, I’m not quite sure what you mean. Are you trying to integrate Facebook onto a site that you built? If that’s what you want, then that’s very easy to do – just go here: http://developers.facebook.com/docs/guides/web – it’s really just some javascript and html if I remember. :) Then people can login, leave comments, “like” things, and so on.

    • Actually, i was trying to built a facebook game for which i require Zynga style login (I think they had used FBML with iframe for Farmville).
      But according to Facebook, we cannot use FBML after 2010 ending, so i had to use IFrame with Javascript SDK of Facebook….

      I was looking for a good example in Python, which i manage to get from Example at Facebook Python-SDK (runwithfriend app)…..

      thnx for ur help…

    • Happy new years, Deepak!

      I’m glad that you got it sorted out. To best honest, I don’t have enough experience with Facebook games, haha (just didn’t really get into them, development or otherwise!)

      If you make something interesting, let me know and maybe we can write a little article about it? ;)
      Graeme

    • Could you elaborate on the error by any chance? Sorry, I’m not keeping track of this application any more. It looks to me though that ((‘/’, Canvas)] should be (‘/’, Canvas)) haha. Very simple typo; if that’s it then i must apologize. I will change it now.

    • Actually, I believe it should be: webapp.WSGIApplication([('/', Canvas)] -> I have updated the post!

  1. Good tutorial.
    I wrote a very simple FB app on GAE last week, just login with FB account and show hello world, it’s normal when visit ***.appspot.com, but when i use apps.facebook.com/***/ , it shows blank page.

    • did u find a solution to this problem, btw how old is this blog post, i did not see any dates.

  2. hey,

    I tried this but when I go to apps.facebook.com/appname it says The server encountered an error and could not complete your request. I see the same message on appname.appspot.com . What am I doing wrong??

    • Hmmm, I’m not sure. I Googled the error, and it seems common – so it may not actually be something wrong with your code, but rather an error with GAE (as unlikely as that seems). Nobody so far has reported an error when they have used this code, but then again maybe they picked up on something and changed it without letting me know. I hope that anyone reading this who knows what’s going on will post a comment about it, because at the moment I don’t actually have this app running, so I can’t check it myself!

      It doesn’t seem like a very useful error does it?

    • Was a solution for this error ever found? I’m new to this and just trying it now and getting the same error:
      “Error: Server Error
      The server encountered an error and could not complete your request.If the problem persists, please report your problem and mention this error message and the query that caused it.”

      For Michael suggestion to try and write a handler… That’s beyond my expertise at the moment. This is why I am currently at this introductory tutorial.

    • I found the cause of the error. Being a newbie, I took the code posted above at face value. I don’t know if it is just my browser or the manner in which the code is posted, but the Python code is not following Python indentation requirements. Just reformat the code with proper Python indentation and it works fine.

      At least it works fine on GAE. The page works fine when I browse the .appspot.com page. However, it just shows a blank iframe when I browse the apps.facebook.com/ page.

      It does appear that the stat counter is incrementing when I browse the apps.facebook.com site. The problem seems to be that the iframe is not displaying the canvas.html visually even though it appears to be handling the functionality of the stat counter.

  3. @bob
    Try write a handler that check’s for both get/and post requests .. since most facebook requests are post … as in use post instead of get …

    • I guess it’s been able to give people the confidence to get their first Facebook app set up, and show them how easy it is to have an app running from AppEngine, and post things to it. From there, they can read from the myriad of other, more advanced tutorials about how to establish a good Facebook App using Python.

  4. Does this method still work? Was trying to set up GAE and facebook and facebook now says I need to provide a secure URL (apparently this requirement came into effect from October 2011).

  5. I have tried your tutorial and it seems to work. When I load it on FB I cannot see anything but reaching the address on AppEngine the counter shows the visit from FB was counted.

    Does Canvas.html need to show any special tags for FB to render it?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>