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():
    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(
            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})

if __name__ == '__main__':

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

    "District Of Columbia",
    "New Hampshire",
    "New Jersey",
    "New Mexico",
    "New York",
    "North Carolina",
    "North Dakota",
    "Rhode Island",
    "South Carolina",
    "South Dakota",
    "West Virginia",

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

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


Leave a comment

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