Susmit Yenkar
Susmit Yenkar

Reputation: 33

Create a POST service in app engine with python

I am very new to app engine and python too so this might sound like a very basic question. I want to create a RESTful service which handles POST requests(using Python, app engine)

For Example:

www.myproject.appspot.com - is my URL

and if I do a simple GET call to this(from a browser or REST client etc), it returns what ever is in the code, like here it is >Hello!<

class MainHandler(webapp2.RequestHandler):
def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write("Hello!")

What I want to do is make it a POST request, like if I hit it with some JSON like

 {"myName" : NameString}

It will print the name in NameString. I know this sounds like a very silly question but please bear with me as my internet search has left me confused with which method to use some have suggested using EndPoints API, Django etc. But I believe my requirement is very basic and webapp2 can handle it.

I just want so direction or basic examples to do this.

Thanks!

Upvotes: 1

Views: 194

Answers (2)

Brent Washburne
Brent Washburne

Reputation: 13158

Here's the way to get the POST data from the request into the response:

class MainHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.POST['myName']
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write("Hello, %s!" % name)

Upvotes: 1

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

Write a method that will handle the POST method and set proper content type:

https://webapp-improved.appspot.com/guide/handlers.html#http-methods-translated-to-class-methods

In your case it would be:

import json
class MainHandler(webapp2.RequestHandler):
  def post(self):
    name = 'John Snow'
    self.response.headers['Content-Type'] = 'application/json'
    self.response.write(json.dumps({"myName" : name}))

Upvotes: 1

Related Questions