pyinat / pyinaturalist

Python client for iNaturalist
https://pyinaturalist.readthedocs.io
MIT License
134 stars 16 forks source link

Add models for API response objects #145

Closed JWCook closed 3 years ago

JWCook commented 3 years ago

I would like to add models for all of our API response objects, as an alternative to working with just JSON. This would be a big improvement toward making this a fully-featured python API client.

To do this I'd like to use the attrs library. It's lightweight, fast, used everywhere (with a subset of very similar features added to the stdlib in 3.7 as dataclasses), integrated with python type annotations and mypy, and makes for super clean code.

Update: see pyinaturalist/models for what I've added so far.

Example

Quick example model for observation comments:

from attr import define, field
from datetime import datetime
from typing import Dict, List

@define
class Comment:
    body: str = field(default=None)
    hidden: bool = field(default=None)
    id: int = field(default=None)
    uuid: str = field(default=None)
    flags: List = field(factory=list)
    moderator_actions: List = field(factory=list)
    created_at: datetime = field(converter=try_datetime, factory=datetime.utcnow)

Some more examples here: naturtag/models.

Benefits

That gives you a ton of features that make responses easier to work with interactively, for example a nice default __str__ method and tab-completion: tabs

More benefits:

Integrating with API functions

This issue will just be for creating the models. Integrating them with the API can be a separate issue. I imagine that can work by either:

  1. Adding an option to pass to existing API functions
  2. Adding wrappers for the API functions to the models (e.g., Observation.search(...))

Tasks

Models:

Other tasks:

JWCook commented 3 years ago

Going to call this one done, and add separate issues for remaining tasks.