Most "pythonic" syntax to use for an API client library

Chris Angelico rosuav at gmail.com
Sun Apr 28 21:54:23 EDT 2019


On Mon, Apr 29, 2019 at 11:44 AM Jonathan Leroy - Inikup via
Python-list <python-list at python.org> wrote:
>
> Hi all,
>
> I'm writing a client library for a REST API. The API endpoints looks like this:
> /customers
> /customers/1
> /customers/1/update
> /customers/1/delete
>
> Which of the following syntax do you expect an API client library to
> use, and why?
>
> 1/
> api.customers_list()
> api.customers_info(1)
> api.customers_update(1, name='Bob')
> api.customers_delete(1)
>
> 2/
> api.customers.list()
> api.customers.info(1)
> api.customers.update(1, name='Bob')
> api.customers.delete(1)
>
> 3/
> api.customers.list()
> api.customers(1).info()
> api.customers(1).update(name='Bob')
> api.customers(1).delete()
>
> ...any other?
>
> #3 seems to be more "pretty" to me, but I did not find any "official"
> recommendation online.
>

Well, it's pretty much up to you; all three of these are reasonable.
I'd base a decision on what "api.customers(1)" would mean. Would that
actually have meaning, or would it be merely a placeholder that
remembers "whatever operation you do, do it to customer 1"? If the
latter, I would be inclined to go with option 2, as it clearly shows
that there will be exactly one API call triggered by that. Also,
option 2 lends itself well to a metaprogramming model, where you can
create a "customers" object, a "documents" object, a "transactions"
object, etc, etc, etc, all from the same class, eg via subclassing
(unless they are SO simple that they can all be completely generic).

ChrisA



More information about the Python-list mailing list