Publish Python objects as RESTful resources over HTTP.
lazr.restful is a library for publishing Python objects through a RESTful web service. To tell lazr.restful which objects you want exposed and how, you annotate your existing Zope interfaces.
The WSGI example web service
The example web service in src/lazr/restful/example/wsgi/ is the best place to start understanding lazr.restful. It’s a very simple web service that uses a subset of lazr.restful’s features and can be run as a standalone WSGI application. An explanation of the code can be found in src/lazr/restful/example/wsgi/README.txt
The full example web service
To understand all of lazr.restful, you should look at the web service defined in src/lazr/restful/example/base/. It defines a simple application serving information about cookbooks and recipes. The interfaces (interfaces.py) are annotated with lazr.restful decorators that say which fields and methods to publish from IRecipe, ICookbook, and so on. The implementations of those interfaces are in root.py.
The machinery of lazr.restful takes the decorators in interfaces.py, and generates an interface that maps incoming HTTP requests to operations on the actual objects defined in root.py. You don’t have to do any HTTP server programming to get it to work (though at the moment you do have to know a fair amount about Zope).
You can test the example web service by running bin/test. The doctests in src/lazr/restful/example/base/tests use a fake httplib2 connection to simulate HTTP requests to the web service. You can watch the tests make GET, PUT, POST, PATCH, and DELETE requests to the web service. Start with root.txt.
Two other pieces of code might be of interest when you’re starting out.
- declarations.py contains all the Python decorators. docs/webservice-declarations.txt shows how to use them.
- docs/webservice.txt shows an example of a webservice that creates Entry and Collection classes directly rather than generating them with the declarations. If you want to use lazr.restful without using zope.schema, this is the test to look at.
NEWS for lazr.restful
Adjust docstring rendering to avoid closing sys.stdout when running under “zope.testrunner –subunit” with docutils >= 0.8.
Fixed bug 1294543: contributes_to can now reference interfaces in other modules and webservice:register directives.
Switch zope.interface, zope.component, and lazr.delegates users from class advice to class decorators.
Restrict find_exported_interfaces to names that would ordinarily be considered to be exported from a module.
Fixed bug 809863: WebServicePublicationMixin.getResouce() converts ComponentLookupErrors to NotFound.
Fixed bug 924291: The FixedVocabularyFieldMarshaller will now correctly return the entire vocabulary if the value passed in is None.
Fixed bug 1020439: The dict marshaller will now correctly unmarshall None.
Fixed bug 1056666: make named operations which result in a resource URL change issue a 301 response containing the new location.
Fixed bug 955668: make marshallers work correctly for collection fields (Set, List, Dict) where the key and/or value types have not been specified. In such cases, the default marshaller is used for the collection elements.
Fixed bug 953587: add a dict marshaller so that exported method parameters can be of type dict.
Fixed bug 871944: a successful write with an If-Match would sometimes return stale values.
Fixed bug 854695: exceptions with no __traceback__ attribute would cause an AttributeError
Fixed bug 842917: multiple values for ws.op in a request would generate a TypeError
Fixed bug 832136: original tracebacks were being obscured when exceptions are rereaised.
A new decorator, @accessor_for, has been added to lazr.restful.declarations. This makes it possible to export a method with bound variables as an accessor for an attribute.
Fixed minor test failures.
The object modification event will not be fired if a client sends an empty changeset via PATCH.
The webservice may define an adapter which is used, after an operation on a resource, to provide notifications consisting of namedtuples (level, message). Any notifications are json encoded and inserted into the response header using the ‘X-Lazr-Notification’ key. They may then be used by the caller to provide extra information to the user about the completed request.
The webservice:json TALES function now returns JSON that will survive HTML escaping.
If the configuration variable require_explicit_versions is set, lazr.restful will not load up a web service unless every field, entry, and named operation explicitly states which version of the web service it first appears in.
When a view is registered for an exception, but the view contains no information that’s useful to lazr.restful, re-raise the exception instead of trying to render the view.
Reverted the client cache representations to JSON-only. Call sites need to escape the JSON_PLUS_XHTML_TYPE representation which may require JSONEncoderForHTML or declaring the the script as CDATA.
Fixed a bug in exception handling when the associated response code is in the 4xx series.
Several of the techniques for associating an exception with an HTTP response code were not working at all. Fixed them.
Add a new test to the testsuite.
Added the ability to get a combined JSON/HTML representation of an entry that has custom HTML representations for some of its fields.
Fixed a bug that prevented a write operation from being promoted to a mutator operation.
0.16.0 (No official release)
If each entry in the web service corresponds to some object on a website, and there’s a way of converting a web service request into a website request, the web service will now provide website links for each entry.
You can suppress the website link for a particular entry class by passing publish_web_link=False into export_as_webservice_entry().
Validation errors for named operations will be properly sent to the client even if they contain Unicode characters. (Launchpad bug 619180.)
Fixed inconsistent handling of custom HTML field renderings. An IFieldHTMLRenderer can now return either Unicode or UTF-8.
lazr.restful will now complain if you try to export an IObject, as this causes infinite recursion during field validation. We had code that worked around the infinite recursion, but it wasn’t reliable and we’ve now removed it to simplify. Use IReference whenever you would use IObject.
lazr.restful gives a more helpful error message when a published interface includes a reference to an unpublished interface. (Launchpad bug 539070)
lazr.restful’s tests now pass in Python 2.7. (Launchpad bug 691841)
Fixed a redirect bug when a web browser requests a representation other than JSON.
Removed overzealous error checking that was causing problems for browsers such as Chromium. (Launchpad bug 423149.)
Added an optimization to the WADL docstring handling that results in a 30% decrease in WADL generation time for large files.
Fixed a unicode encoding bug that precluded reporting exceptions with non-ASCII characters.
Rework ETag generation to be less conservative (an optimization).
Named operations that take URLs as arguments will now accept URLs relative to the versioned service root. Previously they would only accept absolute URLs. PUT and PATCH requests will also accept relative URLs. This fixes bug 497602.
Avoided an error when looking at a Location header that contains characters not valid in URIs. (An error will probably still happen, but having it happen in lazr.restful was confusing people.)
Removed a Python 2.6-ism to restore compatibility with Python 2.5.
Add the ability to annotate an exception so the client will be given the exception message as the HTTP body of the response.
Make WADL generation more deterministic.
Added the ability to take a read-write field and publish it as read-only through the web service.
Optimized lazr.restful to send ‘total_size’ instead of ‘total_size_link’ when ‘total_size’ is easy to calculate, possibly saving the client from sending another HTTP request.
Fixed a bug that prevented first_version_with_total_size_link from working properly in a multi-version environment.
Added an optimization to total_size so that it is fetched via a link when possible. The new configuration option first_version_with_total_size_link specifies what version should be the first to expose the behavior. The default is for it to be enabled for all versions so set this option to preserve the earlier behavior for previously released web services.
Added the ability to mark interface A as a contributor to interface B so that instead of publishing A separately we will add all of A’s fields and operations to the published version of B. Objects implementing B must be adaptable into A for this to work, but lazr.restful will take care of doing the actual adaptation before accessing fields/operations that are not directly provided by an object.
Added invalidation code for the representation cache on events generated by lazr.restful itself. Made the cache more robust and fixed a bug where it would totally redact a forbidden representation rather than simply refuse to serve it. Made it possible for a cache to refuse to cache an object for any reason.
Special note: This version adds a new configuration element, ‘enable_server_side_representation_cache’. This lets you turn the representation cache on and off at runtime without unregistering the cache utility.
Fixed some test failures.
Added the ability to define a representation cache used to store the JSON representations of entry resources, rather than building them from scratch every time. Although the cache has hooks for invalidation, lazr.restful will never invalidate any part of the cache on its own. You need to hook lazr.restful’s invalidation code into your ORM or other data store.
Special note: This version adds a new configuration element, ‘compensate_for_mod_compress_etag_modification’. If you are running lazr.restful behind an Apache server, setting this configuration element will make mod_compress work properly with lazr.restful. This is not a permanent solution: a better solution will be available when Apache bug 39727 is fixed.
Special note: This version removes the configuration element ‘set_hop_to_hop_headers’. You can still define this element in your configuration, but it will have no effect.
Removed code that handles compression through hop-to-hop headers. We’ve never encountered a real situation in which these headers were useful. Compression can and should be handled by intermediaries such as mod_compress. (Unfortunately, mod_compress has its own problems, which this release tries to work around.)
Special note: This version introduces a new configuration element, ‘caching_policy’. This element starts out simple but may become more complex in future versions. See the IWebServiceConfiguration interface for more details.
Service root resources are now client-side cacheable for an amount of time that depends on the server configuration and the version of the web service requested. To get the full benefit, clients will need to upgrade to lazr.restfulclient 0.9.14.
When a PATCH or PUT request changes multiple fields at once, the changes are applied in a deterministic order designed to minimize possible conflicts.
Entry resources will now accept conditional PATCH requests even if one of the resource’s read-only fields has changed behind the scenes recently.
There are two new attributes of the web service configuration, “service_description” and “version_descriptions”. Both are optional, but they’re useful for giving your users an overview of your web service and of the differences between versions.
Special note: this version will break backwards compatibility in your web service unless you take a special step. See “last_version_with_named_mutator_operations” below.
Refactored the code that tags request objects with version information, so that tagging would happen consistently.
By default, mutator methods are no longer separately published as named operations. To maintain backwards compatibility (or if you just want this feature back), put the name of the most recent version of your web service in the “last_version_with_mutator_named_operations” field of your IWebServiceConfiguration implementation.
Fixed a family of bugs that were treating a request originated by a web browser as though it had been originated by a web service client.
Fixed a bug that broke multi-versioned named operations that take the request user as a fixed argument.
A few minor bugfixes to help with Launchpad integration.
Special note: this version contains backwards-incompatible changes. You must change your configuration object to get your code to work in this version! See “active_versions” below.
Added a versioning system for web services. Clients can now request any number of distinct versions as well as a floating “trunk” which is always the most recent version. By using version-aware annotations, developers can publish the same data model differently over time. See the example web service in example/multiversion/ to see how the annotations work.
This release _replaces_ one of the fields in IWebServiceConfiguration. The string ‘service_version_uri’_prefix has become the list ‘active_versions’. The simplest way to deal with this is to just put your ‘service_version_uri_prefix’ into a list and call it ‘active_versions’. We recommend you also add a floating “development” version to the end of ‘active_versions’, calling it something like “devel” or “trunk”. This will give your users a permanent alias to “the most recent version of the web service”.
Fixed a bug that raised an unhandled exception when a client tried to set a URL field to a non-string value.
Fixed a bug rendering the XHTML representation of exproted objects when they contain non-ascii characters.
Corrected a misspelling of the WADL media type.
lazr.restful now runs without deprecation warnings on Python 2.6.
Fixed WADL template: HostedFile DELETE method should have an id of HostedFile-delete, not HostedFile-put.
Transparent compression using Transfer-Encoding is now optional and disabled by default for WSGI applications. (Real WSGI servers don’t allow applications to set hop-by-hop headers like Transfer-Encoding.)
This release introduces a new field to IWebServiceConfiguration: set_hop_by_hop_headers. If you are rolling your own IWebServiceConfiguration implementation, rather than subclassing from BaseWebServiceConfiguration or one of its subclasses, you’ll need to set a value for this. Basically: set it to False if your application is running in a WSGI server, and set it to True otherwise.
Fixed a minor import problem.
lazr.restful runs under Python 2.4 once again.
The authentication-related WSGI middleware classes have been split into a separate project, lazr.authentication.
Fixed a bug that prevented some incoming strings from being loaded by simplejson.
Added WSGI middleware classes for protecting resources with HTTP Basic Auth or OAuth.
Fixed a bug that made it impossible to navigate to a field resource if the field was a link to another object.
Simplified most web service configuration with grok directives.
Added a function that generates a basic WSGI application, given a service root class, a publication class, and a response class.
Added an AbsoluteURL implementation for the simple ServiceRootResource.
Added an adapter from Django’s Manager class to IFiniteSequence, so that services that use Django can serve database objects as collections without special code.
Added an AbsoluteURL implementation for objects that provide more than one URL path for the generated URL.
For services that use Django, added an adapter from Django’s ObjectDoesNotExist to lazr.restful’s NotFoundView.
Fixed some testing infrastructure in lazr.restful.testing.webservice.
Fix some critical packaging problems.
Fixed an import error in simple.py.
Removed a Python 2.6ism from example/wsgi/root.py.
Added a lazr.restful.frameworks.django module to help with publishing Django model objects through lazr.restful web services.
TraverseWithGet implementations now pass the request object into get().
Create a simplified IServiceRootResource implementation for web services that don’t register their top-level collections as Zope utilities.
Make traversal work for entries whose canonical location is beneath another entry.
Raise a ValueError when numberic dates are passed to the DatetimeFieldMarshaller.
Added a second example webservice that works as a standalone WSGI application.
Bug 400170; Stop hacking sys.path in setup.py.
Bug 387487; Allow a subordinate entry resource under a resource where there would normally be a field. Navigation to support subordinate IObjects is added to the publisher.
Declare multipart/form-data as the incoming media type for named operations that include binary fields.
- Initial public release