Writing a module to abstract a REST api
Sven R. Kunze
srkunze at mail.de
Fri Sep 18 19:51:48 CEST 2015
On 18.09.2015 17:28, Joseph L. Casale wrote:
> So a design pattern I use often is to create Python objects to represent
> objects returned from what ever api I am abstracting. For example I
> might create named tuples for static data I dont intend to change or
> for an object I can both query for and create, I might build a class to
> represent it.
> The problem now comes from the following:
> # foo now contains a handle to the remote api.
> foo = InstanceOfApiWrapper()
Is it necessary to have an instance of that API? Just curiosity here.
> # queues is a container of Queue classes.
> queues = foo.get_queues()
> queue = queues
Alright. I see you want to have concrete classes, so you work with HTTP
like you would do with SOAP-bases web services.
I actually was referring to the self-expanding capability of REST
(please note, REST is not HTTP, HTTP is one protocol that can be use to
build an REST-ful API). It's basically like: you query a resource which
holds an link to another resource which you then you query by following
that link and so on and so forth. So, all what you need for REST is one
starting point to explore the resource graph.
> In this case its possible for foo (InstanceOfApiWrapper) to inject a reference
> to itself so the delete() can actually make the call.
> # I want to create a queue from scratch...
> disparate_queue = Queue(x, y, z)
> # Now what happens? No handle to an api?
I don't see an issue here. Looks quite readable.
> An alternative is:
> That's not a pattern I prefer, what facilities in Python provide for a workaround
You always can add attributes to objects. So, add something like an
__api__ attribute (which nobody would ever use except you when creating
these queue objects in "get_queues").
> One option is to put everything in one module and use globals. If the handle is
> initialized it'll just work.
> Problem with that is its not thread safe (without work) and I subscribe to
> one object per file (bloody hard with Python's import/load procedure.
It's perfectly fine to add a "secret" API instance to the object. It's
called aspect-oriented programming. You remove the aspect of how to
correctly manage an API instance and put that knowledge into a separate
piece of code. *thumbs up*
More information about the Python-list