DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Using OpenAI Embeddings Search With SingleStoreDB
  • Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
  • Database Integration Tests With Spring Boot and Testcontainers

Trending

  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Using OpenAI Embeddings Search With SingleStoreDB
  • Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
  • Database Integration Tests With Spring Boot and Testcontainers
  1. DZone
  2. Data Engineering
  3. Databases
  4. Python Rest API Example — Part 3

Python Rest API Example — Part 3

Learn to code your API endpoints in Part 3 of this series on building a Python REST API for your microservices.

Bill Ward user avatar by
Bill Ward
·
Aug. 18, 18 · Tutorial
Like (5)
Save
Tweet
Share
20.31K Views

Join the DZone community and get the full member experience.

Join For Free

With the transition to microservices, it becomes necessary to know how to write simple Rest API's using Python. In this post, I give a python rest API example using Tornado.

This is the third part of this series, where we will code the API endpoints.

Our Python Rest API Example Code

As stated earlier, this post is where we code the endpoint handlers for our microservice. The first handler we will code is the AddHandler class which we will use to add a book.

addhandler.py

import 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)

Notice the initialize method of our class. This is how we pass the instantiated books object to this class so that we can actually do something with it. If we defined a new one here it would instantiate a new Book object for each request. This way we persist the data across the calls as long as the Tornado application is running. A better way to do this is to use a database, but I wanted to keep it simple for this post. In a future post, we will convert this microservice to use a database backend so that the data can persist between application runs.

We use the tornado.web.RequestHandler.get_argument method to get the URL parameters we need to add a book (title and author).

Here is the DelHandler code:

delhandler.py

import 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)

This is very similar to our AddHandler above. We pass it the books object in the initialize method so we can work with it. We also define a parameter "title" which we will use to call the books.del_book(title) method to delete the book. This will return true or false based on whether the book was found and deleted. If True then the book was deleted and we can return an HTTP status of 200 with the book title deletion status. If the book was not found then we return an HTTP status of 404 and write a status that we can't find the book with the given title.

The last handler is the GetHandler which will list out all our books as JSON. This will make it handy to use from other microservices or applications.

gethandler.py

import tornado.web
import book
import json


class GetHandler(tornado.web.RequestHandler):
    def initialize(self, books):
        self.books = books

    def get(self):
        self.write(self.books.json_list())

This our easiest handler because it doesn't take any arguments. We simply call books.json_list() and write the output back to the Request.

Now all you have to do is run the API with the following command:

$ python api.py

Add a book:

http://yourserver:8888/v1/addbook?title="How to Make a Million Dollars Blogging"&author="Bill Ward"

List all the books:

http://yourserver:8888/v1/getbooks

Delete the same book:

http://yourserver:8888/v1/delbook?title="How to Make a Million Dollars Blogging"

There you go. A simple python Rest API example. In the future, I hope to expand on this example by adding a database backend, token security, and more. Subscribe to my newsletter to be notified of all my latest articles.

All of this code is available on GitHub.

I hope you have enjoyed this article — if so, please leave a comment below.

API Python (language) Book

Published at DZone with permission of Bill Ward, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Using OpenAI Embeddings Search With SingleStoreDB
  • Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
  • Database Integration Tests With Spring Boot and Testcontainers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: