Building Lightweight RESTful APIs with CherryPy: A Comprehensive Guide

If you are a Python developer looking to create a lightweight, fast, and self‑contained API without the overhead of a full‑blown web framework like Django or even the bootstrapping needed for Flask, CherryPy offers an elegant alternative. CherryPy is often overlooked in the modern era of asynchronous microframeworks, but it remains a powerful, mature, and remarkably simple tool for building RESTful services. Its built‑in HTTP/1.1‑compliant web server, intuitive routing via object‑oriented dispatch, and minimal boilerplate make it an exceptional choice when you need to expose a small set of endpoints quickly and reliably. Whether you are building an internal microservice, a monitoring dashboard backend, or an IoT data receiver, CherryPy can get you from zero to a working API in minutes.

CherryPy distinguishes itself by embracing a “plain Python” philosophy: you write normal class methods, decorate them with expose, and those methods automatically become HTTP endpoints. The framework handles request parsing, response encoding, and session management behind the scenes, but it never forces you into a specific project layout. You can build a single‑file API or a full modular application. In this tutorial, we will walk through every step needed to create a production‑ready lightweight API using CherryPy. You will learn how to handle different HTTP verbs, parse JSON and form data, return structured responses, add error handling, and configure the server for real‑world use. By the end, you will have a solid understanding of why CherryPy remains a relevant choice for lightweight API development.

Article illustration

Step‑by‑Step Guide: Creating a CherryPy API from Scratch

Step 1: Setting Up the Environment and Installing CherryPy

Before writing any code, you need a Python environment with CherryPy installed. CherryPy requires Python 3.6 or later (Python 3.8+ recommended for the best experience). Create a virtual environment to isolate dependencies: python -m venv cherrypy_api and activate it (on Windows: cherrypy_api\Scripts\activate, on Linux/macOS: source cherrypy_api/bin/activate). Then install CherryPy with pip install cherrypy. That is it – CherryPy is a single package with no additional dependencies, which keeps your project lightweight. To verify the installation, open a Python shell and run import cherrypy; print(cherrypy.__version__). You should see the version number appear. You may also want to install a JSON serializer like ujson for faster performance, but Python’s built‑in json module works perfectly. Your environment is now ready.

Step 2: Writing the Minimal CherryPy Application

The “hello world” of CherryPy is ridiculously short. Create a file named app.py and write the following:

import cherrypy

class HelloWorld:
    @cherrypy.expose
    def index(self):
        return "Hello, CherryPy API!"

if __name__ == '__main__':
    cherrypy.quickstart(HelloWorld())

Run the script with python app.py. CherryPy starts its own web server on http://localhost:8080. Visiting that URL in your browser will display the text. The @cherrypy.expose decorator makes the method accessible via HTTP. The class HelloWorld is a simple resource; its method index maps to the root URL. CherryPy uses the class structure as a URL tree – for example, a method hello inside the class would be at /hello. This object‑oriented routing is one of CherryPy’s defining features and makes it extremely intuitive for organizing API endpoints.

Step 3: Defining API Endpoints with HTTP Methods

For a RESTful API, you need to handle different HTTP verbs (GET, POST, PUT, DELETE). CherryPy does not enforce method‑based routing out of the box, but you can easily implement it by checking cherrypy.request.method inside your exposed method. A cleaner approach is to use the @cherrypy.expose decorator on multiple methods named after the verb, but the canonical way is to leverage CherryPy’s tools or dispatch. For simplicity, we will create a class that handles CRUD operations for a “books” resource. Each method is exposed and contains a conditional branch for the HTTP method:

class Books:
    @cherrypy.expose
    def index(self):
        if cherrypy.request.method == 'GET':
            return self.list_books()
        elif cherrypy.request.method == 'POST':
            return self.create_book()
        elif cherrypy.request.method == 'PUT':
            return self.update_book()
        elif cherrypy.request.method == 'DELETE':
            return self.delete_book()
        else:
            raise cherrypy.HTTPError(405, 'Method not allowed')

    def list_books(self):
        # return list of books in JSON
        return json.dumps(self.get_all_books())
    # ... other helper methods

A more advanced pattern is to define separate methods for each verb and use CherryPy’s dispatcher but for a lightweight API the above pattern is clear and sufficient. You can also use the @cherrypy.expose on a method that is named exactly after the verb (e.g., GET) – CherryPy will call it automatically. The documentation recommends this, and it is cleaner. Let’s rewrite the class using that built‑in convention:

class Books:
    exposed = True

    def GET(self):
        return json.dumps(self.get_all_books())

    def POST(self, title, author):
        # create a new book
        return json.dumps({'status': 'created'})

    def PUT(self, id, title=None, author=None):
        # update book
        return json.dumps({'status': 'updated'})

    def DELETE(self, id):
        # delete book
        return json.dumps({'status': 'deleted'})

Notice the exposed = True class variable – it exposes all methods within that class without needing individual decorators. Each method name corresponds exactly to the HTTP verb. This is the most natural way to build a RESTful API in CherryPy. Additionally, parameters from the query string or form body are automatically passed as method arguments.

Step 4: Handling Request Data – Query Parameters, JSON Bodies, and Forms

CherryPy makes extracting request data extremely straightforward. Query string parameters become keyword arguments to your method. For example, a request to /books?id=5 will pass id='5' to the method. When the client sends a JSON body (common in POST and PUT requests), you need to read the body and parse it. CherryPy provides cherrypy.request.body.params for form parameters, but for raw JSON we use cherrypy.request.body.read() and then json.loads(). To keep the API clean, you can write a small decorator or helper that parses JSON automatically. Here is a typical POST handler that accepts JSON:

import json

def POST(self):
    cl = cherrypy.request.headers.get('Content-Length')
    body = cherrypy.request.body.read(int(cl))
    data = json.loads(body)
    # now use data['title'], data['author']
    return json.dumps({'received': data})

If you want to support both form parameters and JSON, you can check the Content‑Type header. CherryPy also has a built‑in tool called json_in that automatically deserializes JSON request bodies – we will cover tools in the Best Practices section. For now, manually parsing gives you full control. Remember to return a JSON string; CherryPy will set the Content‑Type to text/html by default, so you should set it to application/json explicitly. You can do this by returning a cherrypy.Response object or by using cherrypy.response.headers['Content-Type'] = 'application/json' before returning.

Step 5: Returning Structured Responses – JSON, Status Codes, and Error Handling

An API is only as good as its responses. In CherryPy, you can control the HTTP status code via cherrypy.response.status. For successful creations, set it to 201; for unauthorised access, 401; for not found, 404. Raising cherrypy.HTTPError(status, message) is the standard way to trigger an error response. For example, if a requested book does not exist:

def GET(self, id):
    book = self.find_book(int(id))
    if not book:
        raise cherrypy.HTTPError(404, 'Book not found')
    return json.dumps(book)

CherryPy will automatically generate an error page with the given status code. If you want to return a custom JSON error body, you can catch the error or use the error_page configuration. A common pattern is to wrap all handlers with a try‑except and return a JSON envelope:

@cherrypy.expose
def GET(self, id):
    try:
        book = self.get_book(id)
        if not book:
            raise ValueError('Not found')
        return json.dumps({'success': True, 'data': book})
    except Exception as e:
        cherrypy.response.status = 500
        return json.dumps({'success': False, 'error': str(e)})

This pattern ensures your API always returns JSON, even on errors. You can also use CherryPy’s tools.json_out to automatically serialize your Python dict/list to JSON. With @cherrypy.tools.json_out() decorator (or class variable), you can return a Python dict and CherryPy will convert it to JSON, set the header, and handle encoding. This is the recommended approach for lightweight APIs.

Step 6: Configuring the Server – Port, SSL, and Production Settings

CherryPy’s built‑in server is a production‑grade HTTP server (based on cheroot) that supports SSL, keepalive, and thread pooling. Configuration can be done via a dictionary or a configuration file. To run on a different port or enable SSL, modify the server.socket_port and server.ssl_module settings. Here is an example that runs on port 443 with SSL:

cherrypy.config.update({
    'server.socket_host': '0.0.0.0',
    'server.socket_port': 8080,
    'server.ssl_module': 'builtin',
    'server.ssl_certificate': '/path/to/cert.pem',
    'server.ssl_private_key': '/path/to/key.pem',
})
cherrypy.quickstart(MyAPI())

For production, you also want to set server.thread_pool to a reasonable number (e.g., 10–50) and possibly enable server.socket_timeout. CherryPy can also be mounted behind a reverse proxy (like Nginx) by adjusting cherrypy.server.unsubscribe() and using the WSGI interface. But for a truly lightweight API, the built‑in server is often sufficient. You can also run CherryPy as a WSGI app behind Gunicorn or uWSGI for extra performance.

Step 7: Adding Middleware via CherryPy Tools

CherryPy’s “tools” are hooks that run before or after request handling. They are similar to middleware in other frameworks. Common built‑in tools include json_in, json_out, caching, authentication, gzip, and more. To use them, you can apply them globally, per‑class, or per‑method using decorators. For example, to automatically parse JSON input and output for an entire class:

class Books:
    exposed = True
    tools.json_in.on = True
    tools.json_out.on = True

    def GET(self, id):
        book = self.get_book(id)
        if not book:
            raise cherrypy.HTTPError(404)
        return book  # dict will be converted to JSON

    def POST(self):
        data = cherrypy.request.json  # already parsed
        # create book from data
        return {'status': 'created', 'id': new_id}

You can also create custom tools for authentication, request logging, or rate limiting. This extensibility is one of CherryPy’s strongest features. The tool system is well‑documented and allows you to keep your API code clean while adding cross‑cutting concerns.

Step 8: Packaging and Running the API as a Module

For a real project, you will likely split your API into multiple files. CherryPy supports mounting individual class instances at different URL paths. Suppose you have two resources: Books and Authors. You can mount them like this:

root = Root()
root.books = Books()
root.authors = Authors()
cherrypy.quickstart(root, '/api')

Now /api/books and /api/authors are available. You can also use CherryPy’s cherrypy.tree.mount() to mount independent trees. The final step is to run the server using a startup script. For production, you might want to run CherryPy as a daemon or use a process manager like Supervisord. CherryPy also supports reloading via cherrypy.engine.autoreload during development. Your lightweight API is now complete and ready for deployment.

Tips and Best Practices for CherryPy API Development

Tip 1: Structure Your API with a Clear Separation of Concerns

Even though CherryPy allows you to put everything in one file, for any API with more than a handful of endpoints, you should organize your code into separate modules: one for resource classes, one for database access, one for utilities, and perhaps a configuration file. CherryPy’s mounting mechanism makes it easy to compose a large application from smaller parts. For example, you can create a resources folder with books.py, authors.py, and then import and mount them in your main app.py. This separation improves maintainability and testability. Additionally, consider using a base class or mixins to handle common error formatting, JSON serialization, or session management.

Tip 2: Use Built‑in Tools Instead of Re‑inventing the Wheel

CherryPy ships with a rich set of tools that can save you a lot of code. The json_out and tools have already been mentioned. Additionally, cherrypy.tools.auth_basic provides simple HTTP Basic authentication. cherrypy.tools.caching can add response caching headers. cherrypy.tools.gzip can compress responses automatically. You can also use cherrypy.tools.proxy if your API runs behind a reverse proxy. Before rolling your own solution, check if a built‑in tool does what you need. If you need custom behaviour, you can chain multiple tools or create a new tool class. Tools are powerful and well‑tested.

Tip 3: Always Set the Content‑Type Header Explicitly for API Endpoints

CherryPy defaults to text/html. If you are building a JSON API, you should set the Content‑Type to application/json for every response. The easiest way is to use the @cherrypy.tools.json_out() decorator, which does this automatically. If you manually return a string, you must set cherrypy.response.headers['Content-Type'] = 'application/json'. For error responses, consider returning a JSON body even for 4xx and 5xx errors. You can achieve this by overriding the error_page configuration or by catching exceptions and returning JSON as shown earlier. Clients will appreciate consistent response formats.

Tip 4: Test Your API with Tools Like curl, Postman, or Python Requests

CherryPy uses a synchronous server, so testing is straightforward. During development, you can use curl to simulate requests. For automated testing, Python’s requests library works well with CherryPy’s built‑in server. You can also run CherryPy in a test harness using cherrypy.lib.test_runner or simply start the server in a separate thread and send requests. Because CherryPy is synchronous, you can easily unit‑test individual methods without the server by calling them directly and checking return values. For integration tests, use the webtest library with CherryPy’s WSGI interface. Write tests for all endpoints, including error cases.

Tip 5: Plan for Deployment – Use a Production‑Ready Server or Reverse Proxy

While CherryPy’s built‑in server is robust, for high‑traffic APIs you may want to put it behind a reverse proxy like Nginx or Apache. This allows you to handle SSL termination, load balancing, and static file serving more efficiently. CherryPy can be “unsubscribed” from its own server and mounted as a WSGI application in a container like Gunicorn. For example, gunicorn -w 4 app:application where application is a CherryPy app wrapped in a WSGI handler. Another popular approach is to use CherryPy’s own server behind a proxy – just set cherrypy.server.unsubscribe() and use cherrypy.engine.start() to start the engine without the HTTP server, then run a separate WSGI server. Evaluate your traffic needs and choose accordingly.

FAQ – Frequently Asked Questions About CherryPy APIs

Q1: How does CherryPy compare with Flask for building APIs?

Both are lightweight, but CherryPy is even more minimal in terms of code structure. Flask uses decorators for routing; CherryPy uses object‑oriented mapping. CherryPy comes with its own production‑ready server, while Flask requires a separate WSGI server for production. CherryPy also has a more mature tool system for hooks and middleware. However, Flask has a larger ecosystem of extensions and is more widely used. For a lightweight API that should be self‑contained with no extra dependencies, CherryPy often wins. For projects that may later need a full web application with templates and user authentication, Flask is more common.

Q2: Is CherryPy suitable for building high‑performance APIs?

Yes, CherryPy is designed for performance. Its underlying server, Cheroot, is an asynchronous HTTP server written in pure Python, but it handles concurrency via thread pooling. For most workloads, it performs very well. If you need async I/O or extremely high concurrency (10,000+ simultaneous connections), frameworks like FastAPI or aiohttp may be better. But for typical CRUD APIs with moderate traffic, CherryPy’s performance is more than adequate. You can also use CherryPy as a WSGI app behind a high‑performance server like Gunicorn with workers.

Q3: How do I handle CORS in CherryPy?

CherryPy does not have a built‑in CORS tool, but implementing CORS is straightforward. You can create a custom tool that adds the necessary headers Access‑Control‑Allow‑Origin, Access‑Control‑Allow‑Methods, and Access‑Control‑Allow‑Headers to every response. You also need to handle OPTIONS preflight requests. A simple approach is to write a tool that runs before handler (or after) and sets the headers. For a quick solution, you can add the headers in each endpoint, but a tool is cleaner. Here is a minimal CORS tool:

def cors_tool():
    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
    if cherrypy.request.method == 'OPTIONS':
        cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE'
        cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        return cherrypy.HTTPError(200, 'OK')
cherrypy.tools.cors = cherrypy.Tool('before_handler', cors_tool)

Then apply it globally or per class.

Q4: Can I use CherryPy with an ORM like SQLAlchemy?

Absolutely. CherryPy works seamlessly with SQLAlchemy or any other ORM. You can create a database session on each request (or use scoped sessions) and close it after the response. CherryPy’s tool system is an excellent place to hook into request start and end to manage your session lifecycle. For example, create a tool that opens a session, adds it to cherrypy.request.db, and closes it in a before_finalize hook. Many developers use CherryPy with SQLAlchemy in production. Because CherryPy is synchronous, you do not have to worry about async session management.

Q5: How do I serve static files alongside my API?

CherryPy has built‑in support for static files. You can use the cherrypy.tools.staticdir tool or the static.serve_file function. For example, to serve a static folder at the /files URL, mount a special handler:

import cherrypy
from cherrypy.lib import static

class Static:
    @cherrypy.expose
    def index(self):
        return static.serve_file('/path/to/static', content_type='text/html')
# Or simpler: use the tool
config = {'/files': {'tools.staticdir.on': True, 'tools.staticdir.dir': '/path/to/static'}}
cherrypy.quickstart(MyAPI(), '/', config)

This is useful if you need to serve documentation or a small frontend alongside your API.

Q6: How can I log requests in CherryPy?

CherryPy logs all requests to the built‑in logger (cherrypy.log.access). You can configure its destination (file, stream) and format. Additionally, you can write a custom tool to log extra information (like response time or user ID). For a lightweight API, the default logging is usually sufficient. To add structured logging, you can replace CherryPy’s log handler with your own (e.g., using Python’s logging module with JSON formatter).

Reference Data: Framework Comparison and CherryPy Configuration Options

Table 1: Comparison of Lightweight Python Web Frameworks for API Development
Feature CherryPy Flask FastAPI
Built‑in HTTP server Yes (production‑ready) No (development only) No (Uvicorn/Gunicorn)
Async support No (synchronous only) No (sync, with async extensions) Yes (native async)
Request route definition Object‑oriented classes + @expose Decorators on functions Decorators with type hints
Built‑in JSON tools json_in, json_out tools jsonify() function Automatic (Pydantic)
Middleware system Tools (hooks) Before/after request hooks Middleware classes
Typical code size for simple API Very small (single file) Small (few routes) Small (few routes)
Full‑stack potential Supports templating, sessions, static files Extensions for everything Templating via Jinja2, but not full‑stack
Performance (req/s) Good (thread pool) Good (WSGI) Excellent (async, Starlette)
Table 2: Common CherryPy Server Configuration Options
Config Key Default Value Description
server.socket_host 127.0.0.1 IP address to bind to
server.socket_port 8080 Port to listen on
server.thread_pool 10 Number of worker threads
server.socket_timeout 10 Timeout (seconds) for idle connections
server.ssl_module None ‘builtin’ or ‘pyopenssl’
server.ssl_certificate None Path to SSL certificate file
server.ssl_private_key None Path to SSL private key file
engine.autoreload.on True (dev) Auto‑reload on file changes
log.access_file ” Path to access log file
log.error_file ” Path to error log file
log.screen True Log to console (stderr)

Conclusion

CherryPy may be one of Python’s older web frameworks, but its simplicity, robustness, and “batteries‑included yet lightweight” approach make it an excellent choice for building RESTful APIs that do not require heavy tooling. Throughout this tutorial, you have learned how to set up a CherryPy project, create object‑oriented endpoints that respond to different HTTP verbs, handle request data in various formats, return proper JSON responses with correct status codes, configure the server for production, and leverage built‑in tools to reduce boilerplate. The step‑by‑step process has covered every aspect needed to build a fully functional lightweight API, from a simple hello‑world to a structured multi‑resource service.

The true beauty of CherryPy lies in its minimal learning curve and the fact that you can get an API running with just a few lines of code, yet it scales gracefully for more complex needs. Whether you are prototyping a microservice, building an internal tool, or creating a public API, CherryPy gives you the control and performance you need without forcing you to adopt a massive framework. Combine it with your favourite ORM, authentication library, and deployment strategy, and you have a powerful, lightweight Python API stack. Now go ahead and start building – your next API can be ready in the time it takes to write this article.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *