API reference

This page documents the public surface exposed at the top of the restgdf namespace: the FeatureLayer and Directory entry points, the ArcGISTokenSession wrapper, and the migration helpers in restgdf.compat.

The pydantic response models (LayerMetadata, FeaturesResponse, CrawlReport and friends) live on Pydantic models. Internal utility modules are on Utilities.

FeatureLayer

class restgdf.FeatureLayer(url, session, where='1=1', token=None, **kwargs)[source]

Bases: object

A class for interacting with an ArcGIS REST FeatureLayer.

Variables:
  • metadata (restgdf.LayerMetadata) – Pydantic-validated layer metadata (name, fields, max record count, advanced query capabilities, …). Replaces the pre-2.0 raw dict. Extra keys sent by the server are preserved via extra="allow" and reachable through metadata.model_extra.

  • name (str) – Convenience alias for metadata.name.

  • fields (tuple[str, ]) – Field names consumed by restgdf.

  • object_id_field (str) – Resolved object-id field name ("OBJECTID" when the server omits it).

  • count (int) – Feature count, validated via CountResponse at prep time.

async prep()[source]

Prepare the Rest object.

async classmethod from_url(url, **kwargs)[source]

Create a Rest object from a url.

async get_oids()[source]

Get the object ids for the Rest object.

async sample_gdf(n=10)[source]

Get n random features as a GeoDataFrame.

async head_gdf(n=10)[source]

Get the n first features as a GeoDataFrame.

async get_gdf()[source]

Get a GeoDataFrame from an ArcGIS FeatureLayer.

async row_dict_generator(**kwargs)[source]

Asynchronously yield rows from a GeoDataFrame as dictionaries.

async get_unique_values(fields, sortby=None)[source]

Get the unique values for a field.

async get_value_counts(field)[source]

Get the value counts for a field.

async get_nested_count(fields)[source]

Get the nested value counts for a field.

async getoids()[source]

Deprecated alias for get_oids().

async samplegdf(n=10)[source]

Deprecated alias for sample_gdf().

async headgdf(n=10)[source]

Deprecated alias for head_gdf().

async getgdf()[source]

Deprecated alias for get_gdf().

async getuniquevalues(fields, sortby=None)[source]

Deprecated alias for get_unique_values().

async getvaluecounts(field)[source]

Deprecated alias for get_value_counts().

async getnestedcount(fields)[source]

Deprecated alias for get_nested_count().

async where(wherestr)[source]

Create a new Rest object with a where clause.

Directory

class restgdf.Directory(url, session, token=None)[source]

Bases: object

A class for interacting with ArcGIS Server directories.

Variables:
  • metadata (Optional[restgdf.LayerMetadata]) – Pydantic-validated root metadata populated by prep(). None until prep (or from_url()) has run.

  • services (Optional[list[restgdf.CrawlServiceEntry]]) – Services discovered by the most recent crawl() call. Each entry carries name, url, type, and a parsed metadata (LayerMetadata or None if that service’s metadata call failed).

  • services_with_feature_count (Optional[list[restgdf.CrawlServiceEntry]]) – Same as services but populated with feature counts when crawl() was invoked with return_feature_count=True.

  • report (Optional[restgdf.CrawlReport]) – The full crawl report (services + per-stage errors + root metadata) from the most recent crawl() call. Use this when you need to inspect failures that were silently captured instead of raised.

async prep()[source]
async classmethod from_url(url, **kwargs)[source]

Create a Directory object from a url.

async crawl(return_feature_count=False)[source]
filter_directory_layers(layer_type)[source]
feature_layers()[source]
rasters()[source]

Token session

class restgdf.ArcGISTokenSession(session, credentials=None, token_url='https://www.arcgis.com/sharing/rest/generateToken', token_refresh_threshold=60, token=None, expires=None, verify_ssl=True, config=None)[source]

Bases: object

Wrap an aiohttp session with ArcGIS token refresh behavior.

Construction knobs (token_url, token_refresh_threshold, credentials) are validated via TokenSessionConfig in __post_init__() so a bogus scheme or zero-length username fails fast with RestgdfResponseError rather than surfacing as a 401 or an aiohttp error deep in the request path.

session: ClientSession
credentials: AGOLUserPass | None = None
token_url: str = 'https://www.arcgis.com/sharing/rest/generateToken'
token_refresh_threshold: int = 60
token: str | None = None
expires: int | float | None = None
verify_ssl: bool = True
config: TokenSessionConfig | None = None
property token_request_payload: dict

Return the payload for the token request.

property auth_headers: dict[str, str]

Return authentication headers with the token if available.

update_headers(headers=None)[source]

Return headers merged with the active token.

update_dict(input_dict=None)[source]

Return a request payload/query dict merged with the active token.

async update_token()[source]

Update the token by making a request to the token URL.

The /generateToken payload is validated against TokenResponse (strict tier) so malformed/error envelopes raise RestgdfResponseError instead of KeyError deep in caller code paths.

token_needs_update()[source]

Check if the token needs to be updated.

async update_token_if_needed()[source]

Ensure the token is valid and refresh if necessary.

async get(url, params=None, headers=None, **kwargs)[source]

Make a GET request to the specified URL with the token.

async post(url, data=None, headers=None, **kwargs)[source]

Make a POST request to the specified URL with the token.

Errors

exception restgdf.RestgdfResponseError(message, *, model_name, context, raw)[source]

Bases: ValueError

Raised when a strict-tier ArcGIS response fails validation.

Variables:
  • model_name – The pydantic model class name that rejected the payload (for example "CountResponse").

  • context – A short identifier describing where the response came from (for example the request URL or a helper name). Used by operators triaging ArcGIS vendor variance.

  • raw – The raw JSON-decoded payload that failed validation. Kept on the exception so callers can log or re-raise without re-reading the response body.

Runtime settings

See Pydantic models for the Settings model; the helpers below read it from the environment.

restgdf.get_settings()[source]

Return the process-wide cached Settings instance.

Migration helpers

Compatibility helpers for the 1.x → 2.x migration.

Downstream code that indexed the legacy dict-based public surface (for example metadata["name"], crawl_result["services"]) needs a short-term way to keep working during its own upgrade window. These helpers convert the 2.x pydantic models back into plain Python structures on demand.

They are migration aids, not the primary API — prefer direct attribute access (metadata.name) and model_dump() in new code. These helpers will stay available for the 2.x series but may be removed in 3.x.

restgdf.compat.as_dict(obj)[source]

Return a plain Python dict view of a restgdf pydantic model.

If obj is a pydantic.BaseModel instance, returns obj.model_dump(mode="python", by_alias=False) — a dict keyed by the model’s Python (snake_case) field names, with nested models also recursively dumped.

If obj is anything else (already-a-dict, None, primitive, list), it is returned unchanged. This lets migration code wrap heterogeneous values uniformly:

for entry in report.services:
    row = as_dict(entry)   # dict whether entry is model or already dict
    save(row["name"], row.get("url"))

This helper is intentionally conservative: it does not recurse into containers of models and does not coerce by_alias=True. Callers that need the ArcGIS-native camelCase round-trip should call model_dump() explicitly.

restgdf.compat.as_json_dict(obj)[source]

Return a JSON-safe dict view of a restgdf pydantic model.

Like as_dict(), but uses model_dump(mode="json") so every nested value is a JSON-serializable primitive (SecretStr"**********" placeholder, datetime → ISO string, etc.). Handy for structured logging of a model without carrying unserializable objects into the log record.

Non-model values are returned unchanged.