Cornice Web Services for Pyramid

6.1.0 · active · verified Fri Apr 17

Cornice is a Python library that simplifies the definition of RESTful web services within the Pyramid web framework. It allows developers to declare services, resources, and their methods using decorators and schema validation, often integrating with tools like Colander and Marshmallow. The current version is 6.1.0, and it maintains an active release cadence, frequently updating for Python and Pyramid compatibility and addressing dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple 'Hello World' service using Cornice within a standalone Pyramid application. Run this script, then access `http://0.0.0.0:6543/hello` in your browser or with `curl`.

from wsgiref.simple_server import make_server
from pyramid.config import Configurator

from cornice import Service

# 1. Define a Cornice service
hello_service = Service(name='hello', path='/hello', description="Hello World Service")

@hello_service.get()
def get_hello(request):
    """Returns a 'Hello World!' message."""
    # Access request data via request.GET, request.json, request.validated, etc.
    return {'message': 'Hello World! from Cornice!'}

# 2. Integrate into a Pyramid application
if __name__ == '__main__':
    with Configurator() as config:
        # Include the cornice package to register its components
        config.include('cornice')

        # Add the defined Cornice service to the Pyramid configuration
        config.add_cornice_service(hello_service)

        # Create a WSGI application
        app = config.make_wsgi_app()
    
    # 3. Run the Pyramid application
    server = make_server('0.0.0.0', 6543, app)
    print('Serving on http://0.0.0.0:6543/hello')
    print('Press Ctrl+C to quit')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()

view raw JSON →