How to Create a Simple JSON Service with CherryPy

First make sure you have Python and CherryPy installed.

Then create a Python file containing:

import json
import cherrypy
from cherrypy import tools

def error_page_404(status, message, traceback, version):
    return "404 Error!"

class HomeController():
    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def GetStates(self, **kwargs):
        input_json = cherrypy.request.json
        filter_value = input_json["filter"].lower()

        with open('states.json', 'r') as chat_file:
            states_list = json.loads(chat_file.read())
            states_list = [s.lower() for s in states_list]
            return [s for s in states_list if filter_value in s]

def start_server():
    cherrypy.tree.mount(HomeController(), '/')
    cherrypy.config.update({'error_page.404': error_page_404})
    cherrypy.config.update({'server.socket_port': 9090})
    cherrypy.engine.start()

if __name__ == '__main__':
    start_server()

and a JSON file (e.g. states.json) containing:

[
    "Alabama",
    "Alaska",
    "Arizona",
    "Arkansas",
    "California",
    "Colorado",
    "Connecticut",
    "Delaware",
    "District Of Columbia",
    "Florida",
    "Georgia",
    "Hawaii",
    "Idaho",
    "Illinois",
    "Indiana",
    "Iowa",
    "Kansas",
    "Kentucky",
    "Louisiana",
    "Maine",
    "Maryland",
    "Massachusetts",
    "Michigan",
    "Minnesota",
    "Mississippi",
    "Missouri",
    "Montana",
    "Nebraska",
    "Nevada",
    "New Hampshire",
    "New Jersey",
    "New Mexico",
    "New York",
    "North Carolina",
    "North Dakota",
    "Ohio",
    "Oklahoma",
    "Oregon",
    "Pennsylvania",
    "Rhode Island",
    "South Carolina",
    "South Dakota",
    "Tennessee",
    "Texas",
    "Utah",
    "Vermont",
    "Virginia",
    "Washington",
    "West Virginia",
    "Wisconsin",
    "Wyoming"
]

This service is meant to receive a POST request, which can be tested using the requests library:

import requests

requests.post('http://localhost:9090/GetStates', json={'filter': 'calif'})

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.