Python REST API Example — Part 4: Using JSON Post Data With Python Microservices
So far, we've built a web service for our REST API in Python. Now, we'll add the ability to pass JSON data to an HTTP POST.
Join the DZone community and get the full member experience.
Join For FreeIn this post, we will build on our web service that we made in Parts 1-3 of our Python REST API example by adding the ability to pass JSON data to an HTTP POST.
Add Book Handler
We need to add some code to our Add Handler so that we can deal with JSON. Here is the updated code:
addhandler.pyimport tornado.web
import book
import json
class AddHandler(tornado.web.RequestHandler):
def initialize(self, books):
self.books = books
def get(self):
title = self.get_argument('title')
author = self.get_argument('author')
result = self.books.add_book(title, author)
self.write(result)
def post(self):
data = json.loads(self.request.body)
title = data["title"]
author = data["author"]
result = self.books.add_book(title, author)
self.write(result)
We add a new method called post. We are expecting our body data to contain JSON so we use json.loads to decrypt the JSON into a dict that we can use. This gives us data["title"] for the title and data["author"] for the author. You might have noticed that I don't have any error checking here. It assumes you have the right data in your POST data (title and author). If you don't then Tornado will throw an error and return a 500 result page. After we have our data we can add it to the books object just like we did before in the GET method.
Del Book Handler
We also can update the Del Handler so that we can pass it the book title we want to delete in JSON form in an HTTP POST. Here is the updated code:
delhandler.pyimport tornado.web
import book
import json
class DelHandler(tornado.web.RequestHandler):
def initialize(self, books):
self.books = books
def get(self):
title = self.get_argument('title')
result = self.books.del_book(title)
if result:
self.write("Deleted book title: {0} succsessfully".format(title))
self.set_status(200)
else:
self.write("Book '{0}' not found".format(title))
self.set_status(404)
def post(self):
data = json.loads(self.request.body)
title = data["title"]
result = self.books.del_book(title)
if result:
self.write("Deleted book title: {0} successfully".format(title))
self.set_status(200)
else:
self.write("Book '{0}' not found".format(title))
self.set_status(404)
Much like the addhandler.py code, we are expecting JSON so we need to decode the JSON returned by request.body. Then we set the variable title to data["data"] and do the same bit of code we used in the GET handler.
I hope you have enjoyed this article. If so, please leave a comment below. Thanks again for reading this post.
Published at DZone with permission of Bill Ward, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments