puoygae
puoygae

Reputation: 573

Creating an API with just Google App Engine, webapp2 and Python?

Is it possible to create an API using just webapp2 and Python on Google App Engine?

For example, let's my route /post/123 is handled by this RequestHandler:

class ShowPosts(webapp2.RequestHandler):
    def get(self):
        posts = Post.query().fetch()
        # return the post as data (JSON) here as response 

When a client makes a restful request to /post/123, it can be returned the data object (instead of a rendered html page).

Is this possible or recommended?

Upvotes: 3

Views: 469

Answers (2)

GAEfan
GAEfan

Reputation: 11360

You can build a python list or dict object out of the query, then send it as a JSON object, and send that as the response. Try something like this:

import json

posts     = Post.query()
post_json = []

for post in posts:
    post_dict = {
        'name' : post.name,
        'city' : post.city,
        'state': post.state
    }
    post_json.append( post_dict )

return json.dumps(post_json)

UPDATE: OP asked for example with POST method:

import json

class ShowPosts(webapp2.RequestHandler):
    def get(self):
        posts = Post.query()
        post_json   = []

        for post in posts:
            post_dict = {
                'name' : post.name,
                'city' : post.city,
                'state': post.state
            }

            post_json.append( post_dict )

        return json.dumps(post_json) 

    def post(self):
        posts = Post.query()
        post_json   = []

        for post in posts:
            post_dict = {
                'name' : post.name,
                'city' : post.city,
                'state': post.state
            }

            post_json.append( post_dict )

        post_json.append(
            {
                'posted_name': self.request.get('name'),
                'posted_msg': self.request.get('msg')
            }
        )
        return json.dumps(post_json) 

Upvotes: 5

Ying Li
Ying Li

Reputation: 2519

You don't have to return a HTML page. You can return a JSON, or even just a string since it's your code that you are hosting. You can easily send up an URL with your App Engine that can respond to a REST call.

Upvotes: 1

Related Questions