Skip to content

Files

get, list, all, iter, uploads and downloads use V1: only V1 has a file's person, company or opportunity, and it works under any API version pin. get_download_url uses V2 when it can (one request for the details and a signed URL) and V1 otherwise. feed/iter_feed list every file visible to you, newest first, through V2 (Affinity API 2026-09-17+).

Bases: FileSearchMixin

Service for managing files attached to entities.

Source code in affinity/services/v1_only.py
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
class EntityFileService(FileSearchMixin):
    """Service for managing files attached to entities."""

    def __init__(self, client: HTTPClient):
        self._client = client

    def _validate_exactly_one_target(
        self,
        *,
        person_id: PersonId | None,
        company_id: CompanyId | None,
        opportunity_id: OpportunityId | None,
    ) -> None:
        targets = [person_id, company_id, opportunity_id]
        count = sum(1 for t in targets if t is not None)
        if count == 1:
            return
        if count == 0:
            raise ValueError("Exactly one of person_id, company_id, or opportunity_id is required")
        raise ValueError("Only one of person_id, company_id, or opportunity_id may be provided")

    def list(
        self,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> PaginatedResponse[EntityFile]:
        """Get files attached to an entity."""
        self._validate_exactly_one_target(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )
        params: dict[str, Any] = {}
        if person_id is not None:
            params["person_id"] = int(person_id)
        if company_id is not None:
            params["organization_id"] = int(company_id)
        if opportunity_id is not None:
            params["opportunity_id"] = int(opportunity_id)
        if page_size is not None:
            params["page_size"] = page_size
        if page_token is not None:
            params["page_token"] = page_token

        data = self._client.get("/entity-files", params=params or None, v1=True)
        items = (
            data.get("entity_files")
            or data.get("entityFiles")
            or data.get("files")
            or data.get("data", [])
        )
        if not isinstance(items, list):
            items = []
        return PaginatedResponse[EntityFile](
            data=[EntityFile.model_validate(f) for f in items],
            next_page_token=data.get("next_page_token") or data.get("nextPageToken"),
        )

    def get(self, file_id: FileId) -> EntityFile:
        """A file's details, including the person, company or opportunity it belongs to (V1;
        works under any API version). :meth:`get_download_url` adds a download link."""
        data = self._client.get(f"/entity-files/{file_id}", v1=True)
        return EntityFile.model_validate(data)

    def feed(
        self,
        *,
        created_after: datetime | None = None,
        created_before: datetime | None = None,
        creator_id: UserId | None = None,
        limit: int | None = None,
        total_count: bool = False,
        cursor: str | None = None,
    ) -> PaginatedResponse[FileV2]:
        """One page of the files visible to the caller across the organization, newest first
        (V2, Affinity API 2026-09-17+). V2 can't filter by person, company or opportunity: use
        :meth:`list` for one entity's files. ``limit`` is 1-100."""
        check_cursor_alone(cursor, created_after, created_before, creator_id, limit, total_count)
        if cursor is not None:
            return page_of(
                FileV2, self._client.get_url(cursor, min_api_version=FILES_V2_MIN_API_VERSION)
            )
        params = _file_params(
            created_after=created_after,
            created_before=created_before,
            creator_id=creator_id,
            limit=limit,
            total_count=total_count,
        )
        return page_of(
            FileV2,
            self._client.get(
                "/files", params=params or None, min_api_version=FILES_V2_MIN_API_VERSION
            ),
        )

    def iter_feed(
        self,
        *,
        created_after: datetime | None = None,
        created_before: datetime | None = None,
        creator_id: UserId | None = None,
        limit: int | None = None,
    ) -> Iterator[FileV2]:
        """All files matching the filters (every page); see :meth:`feed`."""

        def fetch_page(next_url: str | None) -> PaginatedResponse[FileV2]:
            if next_url:
                return self.feed(cursor=next_url)
            return self.feed(
                created_after=created_after,
                created_before=created_before,
                creator_id=creator_id,
                limit=limit,
            )

        return PageIterator(fetch_page)

    def download(
        self,
        file_id: FileId,
        *,
        timeout: httpx.Timeout | float | None = None,
        deadline_seconds: float | None = None,
    ) -> bytes:
        """Download file content."""
        return self._client.download_file(
            f"/entity-files/download/{file_id}",
            v1=True,
            timeout=timeout,
            deadline_seconds=deadline_seconds,
        )

    def get_download_url(
        self,
        file_id: FileId,
        *,
        timeout: httpx.Timeout | float | None = None,
    ) -> PresignedUrl:
        """
        Get a presigned download URL for a file without downloading its content.

        The returned URL is valid for approximately 60 seconds and can be
        fetched without authentication (it's self-authenticating via signature).

        Args:
            file_id: The entity file ID
            timeout: Optional request timeout

        Returns:
            PresignedUrl with the URL, file metadata, and expiration info

        Raises:
            AffinityError: If the API doesn't return a redirect URL
        """
        # V2 answers with the details and a signed URL in one request (API 2026-09-17+, beta);
        # a client pinned older, or a V2 refusal, uses V1's details and redirect instead
        try:
            v2 = FileV2.model_validate(
                self._client.get(f"/files/{int(file_id)}", min_api_version=FILES_V2_MIN_API_VERSION)
            )
            if v2.download_url:
                return _presigned(v2.download_url, v2.id, v2.name, v2.size, v2.content_type)
        except (ApiVersionTooOldError, AuthorizationError, NotFoundError):
            pass
        file_meta = self.get(file_id)

        url = self._client.get_redirect_url(
            f"/entity-files/download/{file_id}",
            v1=True,
            timeout=timeout,
        )
        if not url:
            raise AffinityError(
                f"Failed to get presigned URL for file {file_id}: no redirect returned"
            )

        return _presigned(url, file_id, file_meta.name, file_meta.size, file_meta.content_type)

    def download_stream(
        self,
        file_id: FileId,
        *,
        chunk_size: int = 65_536,
        on_progress: ProgressCallback | None = None,
        timeout: httpx.Timeout | float | None = None,
        deadline_seconds: float | None = None,
    ) -> Iterator[bytes]:
        """Stream-download file content in chunks."""
        return self._client.stream_download(
            f"/entity-files/download/{file_id}",
            v1=True,
            chunk_size=chunk_size,
            on_progress=on_progress,
            timeout=timeout,
            deadline_seconds=deadline_seconds,
        )

    def download_stream_with_info(
        self,
        file_id: FileId,
        *,
        chunk_size: int = 65_536,
        on_progress: ProgressCallback | None = None,
        timeout: httpx.Timeout | float | None = None,
        deadline_seconds: float | None = None,
    ) -> DownloadedFile:
        """
        Stream-download a file and return response metadata (headers/filename/size).

        Notes:
        - `filename` is derived from `Content-Disposition` when present.
        - If the server does not provide a filename, callers can fall back to
          `files.get(file_id).name`.
        """
        return self._client.stream_download_with_info(
            f"/entity-files/download/{file_id}",
            v1=True,
            chunk_size=chunk_size,
            on_progress=on_progress,
            timeout=timeout,
            deadline_seconds=deadline_seconds,
        )

    def download_to(
        self,
        file_id: FileId,
        path: str | Path,
        *,
        overwrite: bool = False,
        chunk_size: int = 65_536,
        on_progress: ProgressCallback | None = None,
        timeout: httpx.Timeout | float | None = None,
        deadline_seconds: float | None = None,
    ) -> Path:
        """
        Download a file to disk.

        Args:
            file_id: The entity file id
            path: Destination path
            overwrite: If False, raises FileExistsError when path exists
            chunk_size: Bytes per chunk

        Returns:
            The destination path
        """
        target = Path(path)
        if target.exists() and not overwrite:
            raise FileExistsError(str(target))

        try:
            with target.open("wb") as f:
                for chunk in self.download_stream(
                    file_id,
                    chunk_size=chunk_size,
                    on_progress=on_progress,
                    timeout=timeout,
                    deadline_seconds=deadline_seconds,
                ):
                    f.write(chunk)
        except Exception:
            # Clean up partial file on error
            if target.exists():
                target.unlink()
            raise

        return target

    def _post_upload(
        self,
        files: dict[str, Any],
        *,
        person_id: PersonId | None,
        company_id: CompanyId | None,
        opportunity_id: OpportunityId | None,
    ) -> dict[str, Any]:
        self._validate_exactly_one_target(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )
        return self._client.upload_file(
            "/entity-files",
            files=files,
            data=_upload_target_data(
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
            ),
            v1=True,
        )

    def _post_upload_path(
        self,
        path: str | Path,
        *,
        person_id: PersonId | None,
        company_id: CompanyId | None,
        opportunity_id: OpportunityId | None,
        filename: str | None,
        content_type: str | None,
        on_progress: ProgressCallback | None,
    ) -> dict[str, Any]:
        self._validate_exactly_one_target(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )

        p = Path(path)
        upload_filename = filename or p.name
        guessed, _ = mimetypes.guess_type(upload_filename)
        final_content_type = content_type or guessed or "application/octet-stream"
        total = p.stat().st_size

        if on_progress:
            on_progress(0, total, phase="upload")

        with p.open("rb") as f:
            result = self._post_upload(
                files={"file": (upload_filename, f, final_content_type)},
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
            )

        if on_progress:
            on_progress(total, total, phase="upload")

        return result

    def _post_upload_bytes(
        self,
        data: bytes,
        filename: str,
        *,
        person_id: PersonId | None,
        company_id: CompanyId | None,
        opportunity_id: OpportunityId | None,
        content_type: str | None,
        on_progress: ProgressCallback | None,
    ) -> dict[str, Any]:
        self._validate_exactly_one_target(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )

        guessed, _ = mimetypes.guess_type(filename)
        final_content_type = content_type or guessed or "application/octet-stream"
        total = len(data)

        if on_progress:
            on_progress(0, total, phase="upload")

        result = self._post_upload(
            files={"file": (filename, data, final_content_type)},
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )

        if on_progress:
            on_progress(total, total, phase="upload")

        return result

    def upload(
        self,
        files: dict[str, Any],
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
    ) -> bool:
        """
        Upload files to an entity.

        Args:
            files: Multipart files mapping, e.g. `{"file": (filename, content, content_type)}`
            person_id: Person to attach to
            company_id: Company to attach to
            opportunity_id: Opportunity to attach to

        Returns:
            True when the upload succeeded (the response's `success` flag when
            present). Use `upload_returning_files()` to get the created file records.
        """
        return _upload_succeeded(
            self._post_upload(
                files,
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
            )
        )

    def upload_returning_files(
        self,
        files: dict[str, Any],
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
    ) -> builtins.list[EntityFile]:
        """
        Upload files to an entity and return the created file records.

        Same request as `upload()`; returns the `entity_files` from the response,
        so the new file ids can be used with `get()`/`download()` straight away.

        Returns:
            The created files. Empty if the API returned no `entity_files` (older
            responses were just `{"success": true}`). Never raises after a successful
            (2xx) upload: an entry that fails validation is returned as a partial
            record (unvalidated; fields that failed are None) when it has an id,
            and skipped otherwise.
        """
        return _parse_uploaded_files(
            self._post_upload(
                files,
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
            )
        )

    def upload_path(
        self,
        path: str | Path,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
        filename: str | None = None,
        content_type: str | None = None,
        on_progress: ProgressCallback | None = None,
    ) -> bool:
        """
        Upload a file from disk.

        Notes:
        - Returns True when the upload succeeded. Use `upload_path_returning_files()`
          to get the created file record (with its id).
        - Progress reporting is best-effort for uploads (start/end only).
        """
        return _upload_succeeded(
            self._post_upload_path(
                path,
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
                filename=filename,
                content_type=content_type,
                on_progress=on_progress,
            )
        )

    def upload_path_returning_files(
        self,
        path: str | Path,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
        filename: str | None = None,
        content_type: str | None = None,
        on_progress: ProgressCallback | None = None,
    ) -> builtins.list[EntityFile]:
        """
        Upload a file from disk and return the created file records.

        Same as `upload_path()`, but returns the response's `entity_files`
        (see `upload_returning_files()` for the parsing rules).
        """
        return _parse_uploaded_files(
            self._post_upload_path(
                path,
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
                filename=filename,
                content_type=content_type,
                on_progress=on_progress,
            )
        )

    def upload_bytes(
        self,
        data: bytes,
        filename: str,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
        content_type: str | None = None,
        on_progress: ProgressCallback | None = None,
    ) -> bool:
        """
        Upload in-memory bytes as a file.

        Notes:
        - Returns True when the upload succeeded. Use `upload_bytes_returning_files()`
          to get the created file record (with its id).
        - Progress reporting is best-effort for uploads (start/end only).
        """
        return _upload_succeeded(
            self._post_upload_bytes(
                data,
                filename,
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
                content_type=content_type,
                on_progress=on_progress,
            )
        )

    def upload_bytes_returning_files(
        self,
        data: bytes,
        filename: str,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
        content_type: str | None = None,
        on_progress: ProgressCallback | None = None,
    ) -> builtins.list[EntityFile]:
        """
        Upload in-memory bytes as a file and return the created file records.

        Same as `upload_bytes()`, but returns the response's `entity_files`
        (see `upload_returning_files()` for the parsing rules).
        """
        return _parse_uploaded_files(
            self._post_upload_bytes(
                data,
                filename,
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
                content_type=content_type,
                on_progress=on_progress,
            )
        )

    def all(
        self,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
    ) -> Iterator[EntityFile]:
        """Iterate through all files for an entity with automatic pagination."""
        self._validate_exactly_one_target(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )

        page_token: str | None = None
        while True:
            page = self.list(
                person_id=person_id,
                company_id=company_id,
                opportunity_id=opportunity_id,
                page_token=page_token,
            )
            yield from page.data
            if not page.has_next:
                break
            page_token = page.next_page_token

    def iter(
        self,
        *,
        person_id: PersonId | None = None,
        company_id: CompanyId | None = None,
        opportunity_id: OpportunityId | None = None,
    ) -> Iterator[EntityFile]:
        """Auto-paginate all files (alias for `all()`)."""
        return self.all(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )

all(*, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None) -> Iterator[EntityFile]

Iterate through all files for an entity with automatic pagination.

Source code in affinity/services/v1_only.py
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
def all(
    self,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
) -> Iterator[EntityFile]:
    """Iterate through all files for an entity with automatic pagination."""
    self._validate_exactly_one_target(
        person_id=person_id,
        company_id=company_id,
        opportunity_id=opportunity_id,
    )

    page_token: str | None = None
    while True:
        page = self.list(
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
            page_token=page_token,
        )
        yield from page.data
        if not page.has_next:
            break
        page_token = page.next_page_token

download(file_id: FileId, *, timeout: httpx.Timeout | float | None = None, deadline_seconds: float | None = None) -> bytes

Download file content.

Source code in affinity/services/v1_only.py
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
def download(
    self,
    file_id: FileId,
    *,
    timeout: httpx.Timeout | float | None = None,
    deadline_seconds: float | None = None,
) -> bytes:
    """Download file content."""
    return self._client.download_file(
        f"/entity-files/download/{file_id}",
        v1=True,
        timeout=timeout,
        deadline_seconds=deadline_seconds,
    )

download_stream(file_id: FileId, *, chunk_size: int = 65536, on_progress: ProgressCallback | None = None, timeout: httpx.Timeout | float | None = None, deadline_seconds: float | None = None) -> Iterator[bytes]

Stream-download file content in chunks.

Source code in affinity/services/v1_only.py
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
def download_stream(
    self,
    file_id: FileId,
    *,
    chunk_size: int = 65_536,
    on_progress: ProgressCallback | None = None,
    timeout: httpx.Timeout | float | None = None,
    deadline_seconds: float | None = None,
) -> Iterator[bytes]:
    """Stream-download file content in chunks."""
    return self._client.stream_download(
        f"/entity-files/download/{file_id}",
        v1=True,
        chunk_size=chunk_size,
        on_progress=on_progress,
        timeout=timeout,
        deadline_seconds=deadline_seconds,
    )

download_stream_with_info(file_id: FileId, *, chunk_size: int = 65536, on_progress: ProgressCallback | None = None, timeout: httpx.Timeout | float | None = None, deadline_seconds: float | None = None) -> DownloadedFile

Stream-download a file and return response metadata (headers/filename/size).

Notes: - filename is derived from Content-Disposition when present. - If the server does not provide a filename, callers can fall back to files.get(file_id).name.

Source code in affinity/services/v1_only.py
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
def download_stream_with_info(
    self,
    file_id: FileId,
    *,
    chunk_size: int = 65_536,
    on_progress: ProgressCallback | None = None,
    timeout: httpx.Timeout | float | None = None,
    deadline_seconds: float | None = None,
) -> DownloadedFile:
    """
    Stream-download a file and return response metadata (headers/filename/size).

    Notes:
    - `filename` is derived from `Content-Disposition` when present.
    - If the server does not provide a filename, callers can fall back to
      `files.get(file_id).name`.
    """
    return self._client.stream_download_with_info(
        f"/entity-files/download/{file_id}",
        v1=True,
        chunk_size=chunk_size,
        on_progress=on_progress,
        timeout=timeout,
        deadline_seconds=deadline_seconds,
    )

download_to(file_id: FileId, path: str | Path, *, overwrite: bool = False, chunk_size: int = 65536, on_progress: ProgressCallback | None = None, timeout: httpx.Timeout | float | None = None, deadline_seconds: float | None = None) -> Path

Download a file to disk.

Parameters:

Name Type Description Default
file_id FileId

The entity file id

required
path str | Path

Destination path

required
overwrite bool

If False, raises FileExistsError when path exists

False
chunk_size int

Bytes per chunk

65536

Returns:

Type Description
Path

The destination path

Source code in affinity/services/v1_only.py
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def download_to(
    self,
    file_id: FileId,
    path: str | Path,
    *,
    overwrite: bool = False,
    chunk_size: int = 65_536,
    on_progress: ProgressCallback | None = None,
    timeout: httpx.Timeout | float | None = None,
    deadline_seconds: float | None = None,
) -> Path:
    """
    Download a file to disk.

    Args:
        file_id: The entity file id
        path: Destination path
        overwrite: If False, raises FileExistsError when path exists
        chunk_size: Bytes per chunk

    Returns:
        The destination path
    """
    target = Path(path)
    if target.exists() and not overwrite:
        raise FileExistsError(str(target))

    try:
        with target.open("wb") as f:
            for chunk in self.download_stream(
                file_id,
                chunk_size=chunk_size,
                on_progress=on_progress,
                timeout=timeout,
                deadline_seconds=deadline_seconds,
            ):
                f.write(chunk)
    except Exception:
        # Clean up partial file on error
        if target.exists():
            target.unlink()
        raise

    return target

feed(*, created_after: datetime | None = None, created_before: datetime | None = None, creator_id: UserId | None = None, limit: int | None = None, total_count: bool = False, cursor: str | None = None) -> PaginatedResponse[FileV2]

One page of the files visible to the caller across the organization, newest first (V2, Affinity API 2026-09-17+). V2 can't filter by person, company or opportunity: use :meth:list for one entity's files. limit is 1-100.

Source code in affinity/services/v1_only.py
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
def feed(
    self,
    *,
    created_after: datetime | None = None,
    created_before: datetime | None = None,
    creator_id: UserId | None = None,
    limit: int | None = None,
    total_count: bool = False,
    cursor: str | None = None,
) -> PaginatedResponse[FileV2]:
    """One page of the files visible to the caller across the organization, newest first
    (V2, Affinity API 2026-09-17+). V2 can't filter by person, company or opportunity: use
    :meth:`list` for one entity's files. ``limit`` is 1-100."""
    check_cursor_alone(cursor, created_after, created_before, creator_id, limit, total_count)
    if cursor is not None:
        return page_of(
            FileV2, self._client.get_url(cursor, min_api_version=FILES_V2_MIN_API_VERSION)
        )
    params = _file_params(
        created_after=created_after,
        created_before=created_before,
        creator_id=creator_id,
        limit=limit,
        total_count=total_count,
    )
    return page_of(
        FileV2,
        self._client.get(
            "/files", params=params or None, min_api_version=FILES_V2_MIN_API_VERSION
        ),
    )

get(file_id: FileId) -> EntityFile

A file's details, including the person, company or opportunity it belongs to (V1; works under any API version). :meth:get_download_url adds a download link.

Source code in affinity/services/v1_only.py
1969
1970
1971
1972
1973
def get(self, file_id: FileId) -> EntityFile:
    """A file's details, including the person, company or opportunity it belongs to (V1;
    works under any API version). :meth:`get_download_url` adds a download link."""
    data = self._client.get(f"/entity-files/{file_id}", v1=True)
    return EntityFile.model_validate(data)

get_download_url(file_id: FileId, *, timeout: httpx.Timeout | float | None = None) -> PresignedUrl

Get a presigned download URL for a file without downloading its content.

The returned URL is valid for approximately 60 seconds and can be fetched without authentication (it's self-authenticating via signature).

Parameters:

Name Type Description Default
file_id FileId

The entity file ID

required
timeout Timeout | float | None

Optional request timeout

None

Returns:

Type Description
PresignedUrl

PresignedUrl with the URL, file metadata, and expiration info

Raises:

Type Description
AffinityError

If the API doesn't return a redirect URL

Source code in affinity/services/v1_only.py
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
def get_download_url(
    self,
    file_id: FileId,
    *,
    timeout: httpx.Timeout | float | None = None,
) -> PresignedUrl:
    """
    Get a presigned download URL for a file without downloading its content.

    The returned URL is valid for approximately 60 seconds and can be
    fetched without authentication (it's self-authenticating via signature).

    Args:
        file_id: The entity file ID
        timeout: Optional request timeout

    Returns:
        PresignedUrl with the URL, file metadata, and expiration info

    Raises:
        AffinityError: If the API doesn't return a redirect URL
    """
    # V2 answers with the details and a signed URL in one request (API 2026-09-17+, beta);
    # a client pinned older, or a V2 refusal, uses V1's details and redirect instead
    try:
        v2 = FileV2.model_validate(
            self._client.get(f"/files/{int(file_id)}", min_api_version=FILES_V2_MIN_API_VERSION)
        )
        if v2.download_url:
            return _presigned(v2.download_url, v2.id, v2.name, v2.size, v2.content_type)
    except (ApiVersionTooOldError, AuthorizationError, NotFoundError):
        pass
    file_meta = self.get(file_id)

    url = self._client.get_redirect_url(
        f"/entity-files/download/{file_id}",
        v1=True,
        timeout=timeout,
    )
    if not url:
        raise AffinityError(
            f"Failed to get presigned URL for file {file_id}: no redirect returned"
        )

    return _presigned(url, file_id, file_meta.name, file_meta.size, file_meta.content_type)

iter(*, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None) -> Iterator[EntityFile]

Auto-paginate all files (alias for all()).

Source code in affinity/services/v1_only.py
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
def iter(
    self,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
) -> Iterator[EntityFile]:
    """Auto-paginate all files (alias for `all()`)."""
    return self.all(
        person_id=person_id,
        company_id=company_id,
        opportunity_id=opportunity_id,
    )

iter_feed(*, created_after: datetime | None = None, created_before: datetime | None = None, creator_id: UserId | None = None, limit: int | None = None) -> Iterator[FileV2]

All files matching the filters (every page); see :meth:feed.

Source code in affinity/services/v1_only.py
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
def iter_feed(
    self,
    *,
    created_after: datetime | None = None,
    created_before: datetime | None = None,
    creator_id: UserId | None = None,
    limit: int | None = None,
) -> Iterator[FileV2]:
    """All files matching the filters (every page); see :meth:`feed`."""

    def fetch_page(next_url: str | None) -> PaginatedResponse[FileV2]:
        if next_url:
            return self.feed(cursor=next_url)
        return self.feed(
            created_after=created_after,
            created_before=created_before,
            creator_id=creator_id,
            limit=limit,
        )

    return PageIterator(fetch_page)

list(*, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None, page_size: int | None = None, page_token: str | None = None) -> PaginatedResponse[EntityFile]

Get files attached to an entity.

Source code in affinity/services/v1_only.py
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
def list(
    self,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
    page_size: int | None = None,
    page_token: str | None = None,
) -> PaginatedResponse[EntityFile]:
    """Get files attached to an entity."""
    self._validate_exactly_one_target(
        person_id=person_id,
        company_id=company_id,
        opportunity_id=opportunity_id,
    )
    params: dict[str, Any] = {}
    if person_id is not None:
        params["person_id"] = int(person_id)
    if company_id is not None:
        params["organization_id"] = int(company_id)
    if opportunity_id is not None:
        params["opportunity_id"] = int(opportunity_id)
    if page_size is not None:
        params["page_size"] = page_size
    if page_token is not None:
        params["page_token"] = page_token

    data = self._client.get("/entity-files", params=params or None, v1=True)
    items = (
        data.get("entity_files")
        or data.get("entityFiles")
        or data.get("files")
        or data.get("data", [])
    )
    if not isinstance(items, list):
        items = []
    return PaginatedResponse[EntityFile](
        data=[EntityFile.model_validate(f) for f in items],
        next_page_token=data.get("next_page_token") or data.get("nextPageToken"),
    )

upload(files: dict[str, Any], *, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None) -> bool

Upload files to an entity.

Parameters:

Name Type Description Default
files dict[str, Any]

Multipart files mapping, e.g. {"file": (filename, content, content_type)}

required
person_id PersonId | None

Person to attach to

None
company_id CompanyId | None

Company to attach to

None
opportunity_id OpportunityId | None

Opportunity to attach to

None

Returns:

Type Description
bool

True when the upload succeeded (the response's success flag when

bool

present). Use upload_returning_files() to get the created file records.

Source code in affinity/services/v1_only.py
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
def upload(
    self,
    files: dict[str, Any],
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
) -> bool:
    """
    Upload files to an entity.

    Args:
        files: Multipart files mapping, e.g. `{"file": (filename, content, content_type)}`
        person_id: Person to attach to
        company_id: Company to attach to
        opportunity_id: Opportunity to attach to

    Returns:
        True when the upload succeeded (the response's `success` flag when
        present). Use `upload_returning_files()` to get the created file records.
    """
    return _upload_succeeded(
        self._post_upload(
            files,
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )
    )

upload_bytes(data: bytes, filename: str, *, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None, content_type: str | None = None, on_progress: ProgressCallback | None = None) -> bool

Upload in-memory bytes as a file.

Notes: - Returns True when the upload succeeded. Use upload_bytes_returning_files() to get the created file record (with its id). - Progress reporting is best-effort for uploads (start/end only).

Source code in affinity/services/v1_only.py
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
def upload_bytes(
    self,
    data: bytes,
    filename: str,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
    content_type: str | None = None,
    on_progress: ProgressCallback | None = None,
) -> bool:
    """
    Upload in-memory bytes as a file.

    Notes:
    - Returns True when the upload succeeded. Use `upload_bytes_returning_files()`
      to get the created file record (with its id).
    - Progress reporting is best-effort for uploads (start/end only).
    """
    return _upload_succeeded(
        self._post_upload_bytes(
            data,
            filename,
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
            content_type=content_type,
            on_progress=on_progress,
        )
    )

upload_bytes_returning_files(data: bytes, filename: str, *, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None, content_type: str | None = None, on_progress: ProgressCallback | None = None) -> builtins.list[EntityFile]

Upload in-memory bytes as a file and return the created file records.

Same as upload_bytes(), but returns the response's entity_files (see upload_returning_files() for the parsing rules).

Source code in affinity/services/v1_only.py
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
def upload_bytes_returning_files(
    self,
    data: bytes,
    filename: str,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
    content_type: str | None = None,
    on_progress: ProgressCallback | None = None,
) -> builtins.list[EntityFile]:
    """
    Upload in-memory bytes as a file and return the created file records.

    Same as `upload_bytes()`, but returns the response's `entity_files`
    (see `upload_returning_files()` for the parsing rules).
    """
    return _parse_uploaded_files(
        self._post_upload_bytes(
            data,
            filename,
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
            content_type=content_type,
            on_progress=on_progress,
        )
    )

upload_path(path: str | Path, *, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None, filename: str | None = None, content_type: str | None = None, on_progress: ProgressCallback | None = None) -> bool

Upload a file from disk.

Notes: - Returns True when the upload succeeded. Use upload_path_returning_files() to get the created file record (with its id). - Progress reporting is best-effort for uploads (start/end only).

Source code in affinity/services/v1_only.py
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
def upload_path(
    self,
    path: str | Path,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
    filename: str | None = None,
    content_type: str | None = None,
    on_progress: ProgressCallback | None = None,
) -> bool:
    """
    Upload a file from disk.

    Notes:
    - Returns True when the upload succeeded. Use `upload_path_returning_files()`
      to get the created file record (with its id).
    - Progress reporting is best-effort for uploads (start/end only).
    """
    return _upload_succeeded(
        self._post_upload_path(
            path,
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
            filename=filename,
            content_type=content_type,
            on_progress=on_progress,
        )
    )

upload_path_returning_files(path: str | Path, *, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None, filename: str | None = None, content_type: str | None = None, on_progress: ProgressCallback | None = None) -> builtins.list[EntityFile]

Upload a file from disk and return the created file records.

Same as upload_path(), but returns the response's entity_files (see upload_returning_files() for the parsing rules).

Source code in affinity/services/v1_only.py
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
def upload_path_returning_files(
    self,
    path: str | Path,
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
    filename: str | None = None,
    content_type: str | None = None,
    on_progress: ProgressCallback | None = None,
) -> builtins.list[EntityFile]:
    """
    Upload a file from disk and return the created file records.

    Same as `upload_path()`, but returns the response's `entity_files`
    (see `upload_returning_files()` for the parsing rules).
    """
    return _parse_uploaded_files(
        self._post_upload_path(
            path,
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
            filename=filename,
            content_type=content_type,
            on_progress=on_progress,
        )
    )

upload_returning_files(files: dict[str, Any], *, person_id: PersonId | None = None, company_id: CompanyId | None = None, opportunity_id: OpportunityId | None = None) -> builtins.list[EntityFile]

Upload files to an entity and return the created file records.

Same request as upload(); returns the entity_files from the response, so the new file ids can be used with get()/download() straight away.

Returns:

Type Description
list[EntityFile]

The created files. Empty if the API returned no entity_files (older

list[EntityFile]

responses were just {"success": true}). Never raises after a successful

list[EntityFile]

(2xx) upload: an entry that fails validation is returned as a partial

list[EntityFile]

record (unvalidated; fields that failed are None) when it has an id,

list[EntityFile]

and skipped otherwise.

Source code in affinity/services/v1_only.py
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
def upload_returning_files(
    self,
    files: dict[str, Any],
    *,
    person_id: PersonId | None = None,
    company_id: CompanyId | None = None,
    opportunity_id: OpportunityId | None = None,
) -> builtins.list[EntityFile]:
    """
    Upload files to an entity and return the created file records.

    Same request as `upload()`; returns the `entity_files` from the response,
    so the new file ids can be used with `get()`/`download()` straight away.

    Returns:
        The created files. Empty if the API returned no `entity_files` (older
        responses were just `{"success": true}`). Never raises after a successful
        (2xx) upload: an entry that fails validation is returned as a partial
        record (unvalidated; fields that failed are None) when it has an id,
        and skipped otherwise.
    """
    return _parse_uploaded_files(
        self._post_upload(
            files,
            person_id=person_id,
            company_id=company_id,
            opportunity_id=opportunity_id,
        )
    )