xippios-x 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xippios/x/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """Public API: ``__version__`` and the task functions re-exported here (conventions §2).
2
+
3
+ Upstream: X API v2. Each task returns ``Result[T]``, ``T`` the page X answers with, whose
4
+ models are re-exported too, with the parameter enum ``Granularity``; the endpoint wrappers
5
+ are ``xippios.x.api``.
6
+ """
7
+
8
+ from xippios.x._version import __version__
9
+ from xippios.x.models import (
10
+ GetListsPostsResponse,
11
+ GetPostsCountsAllResponse,
12
+ GetUsageResponse,
13
+ GetUsersByUsernamesResponse,
14
+ GetUsersPostsResponse,
15
+ Granularity,
16
+ Post,
17
+ Problem,
18
+ SearchPostsRecentResponse,
19
+ Usage,
20
+ User,
21
+ )
22
+ from xippios.x.tasks import (
23
+ count_posts,
24
+ get_conversation_posts,
25
+ get_list_posts,
26
+ get_usage,
27
+ get_user_posts,
28
+ lookup_users,
29
+ search_recent_posts,
30
+ )
31
+
32
+ __all__ = [
33
+ "GetListsPostsResponse",
34
+ "GetPostsCountsAllResponse",
35
+ "GetUsageResponse",
36
+ "GetUsersByUsernamesResponse",
37
+ "GetUsersPostsResponse",
38
+ "Granularity",
39
+ "Post",
40
+ "Problem",
41
+ "SearchPostsRecentResponse",
42
+ "Usage",
43
+ "User",
44
+ "__version__",
45
+ "count_posts",
46
+ "get_conversation_posts",
47
+ "get_list_posts",
48
+ "get_usage",
49
+ "get_user_posts",
50
+ "lookup_users",
51
+ "search_recent_posts",
52
+ ]
xippios/x/_client.py ADDED
@@ -0,0 +1,198 @@
1
+ """The package's one configured ``AsyncClient`` and its error mapping (conventions §6)."""
2
+
3
+ import json
4
+ import time
5
+
6
+ import httpx
7
+ from xippios.core import (
8
+ AsyncClient,
9
+ BearerAuth,
10
+ ClientConfig,
11
+ InvalidRequestError,
12
+ NotFoundError,
13
+ RateLimit,
14
+ RateLimitError,
15
+ XippiosError,
16
+ )
17
+
18
+ from xippios.x._version import __version__
19
+
20
+ SOURCE = "x"
21
+ BASE_URL = "https://api.x.com/2"
22
+ API_KEY_ENV = "X_API_KEY" # pragma: allowlist secret (a variable name, not a key)
23
+ # A self-imposed pace (ADR-0010 decision 1): X documents no per-minute limit, only
24
+ # per-endpoint windows of 15 minutes per app (docs/upstream/pages/rate-limits.md), and a
25
+ # 1/sec limit on two endpoints this package does not wrap (GET /2/tweets/search/all and
26
+ # GET /2/spaces/by/creator_ids). The windows are spent, not rationed (ADR-0010 decision 2):
27
+ # classify turns their 429 into RateLimitError with retry_after (coordination row 304).
28
+ RATE_LIMIT = RateLimit(per_minute=60, burst=1)
29
+
30
+ RATE_LIMIT_WINDOW = 900.0
31
+ """Seconds of X's per-endpoint rate-limit window, 15 minutes (``pages/rate-limits.md``).
32
+
33
+ The wait ``classify`` gives a 429 whose ``x-rate-limit-reset`` is missing or unreadable.
34
+ """
35
+ BILLING_CYCLE = 31 * 86_400.0
36
+ """Seconds of the longest monthly billing cycle, 31 days: the wait of a ``usage-capped``.
37
+
38
+ X blocks requests "until the next billing cycle" once a spending limit is reached, and
39
+ caps pay-per-usage plans per "monthly billing cycle" (``pages/pricing.md``); its answer
40
+ does not say when the cycle starts, so the wait is the longest a cycle can last.
41
+ """
42
+
43
+ _INVALID_REQUEST = frozenset({"invalid-request"})
44
+ _NOT_FOUND = frozenset({"resource-not-found"})
45
+ _RATE_LIMITED = frozenset({"rate-limit-exceeded"})
46
+ _USAGE_CAPPED = frozenset({"usage-capped"})
47
+ _SNIPPET = 300
48
+
49
+
50
+ def _payload(response: httpx.Response) -> dict[str, object]:
51
+ """The body as a JSON object, else an empty mapping."""
52
+ try:
53
+ payload = json.loads(response.content)
54
+ except ValueError:
55
+ return {}
56
+ return payload if isinstance(payload, dict) else {}
57
+
58
+
59
+ def _problem_type(payload: dict[str, object]) -> str | None:
60
+ """The last segment of the problem's ``type`` URI, e.g. ``"invalid-request"``.
61
+
62
+ X writes the URI on either host (``https://api.x.com/2/problems/...``, and
63
+ ``https://api.twitter.com/2/problems/...`` in the OpenAPI document's rule problems),
64
+ so only the segment is compared. A body without ``type`` gives the type of its first
65
+ ``errors`` entry that has one, else ``None``.
66
+ """
67
+ candidates: list[object] = [payload.get("type")]
68
+ errors = payload.get("errors")
69
+ if isinstance(errors, list):
70
+ candidates += [item.get("type") for item in errors if isinstance(item, dict)]
71
+ for value in candidates:
72
+ if isinstance(value, str) and value:
73
+ return value.rstrip("/").rsplit("/", 1)[-1]
74
+ return None
75
+
76
+
77
+ def _details(payload: dict[str, object]) -> str:
78
+ """Upstream's words: ``title``, ``detail`` and each ``errors`` entry's message or detail."""
79
+ parts = [
80
+ str(payload[name])
81
+ for name in ("title", "detail")
82
+ if isinstance(payload.get(name), str) and payload[name]
83
+ ]
84
+ errors = payload.get("errors")
85
+ if isinstance(errors, list):
86
+ for item in errors:
87
+ if not isinstance(item, dict):
88
+ continue
89
+ text = item.get("message") or item.get("detail")
90
+ if isinstance(text, str) and text and text not in parts:
91
+ parts.append(text)
92
+ joined = " ".join("; ".join(parts).split())
93
+ return joined[:_SNIPPET]
94
+
95
+
96
+ def _where(response: httpx.Response) -> str:
97
+ # Method and path only: the query is never quoted (conventions §5, ADR-0005).
98
+ return f"{response.request.method} {response.request.url.path}"
99
+
100
+
101
+ def _until_reset(response: httpx.Response) -> float:
102
+ """Seconds until ``x-rate-limit-reset``, a Unix timestamp, never negative.
103
+
104
+ ``RATE_LIMIT_WINDOW``, the 15-minute window, when the header is missing or is not
105
+ ASCII digits.
106
+ """
107
+ reset = response.headers.get("x-rate-limit-reset", "").strip()
108
+ if not (reset.isascii() and reset.isdigit()):
109
+ return RATE_LIMIT_WINDOW
110
+ return max(0.0, float(reset) - time.time())
111
+
112
+
113
+ def classify(response: httpx.Response) -> XippiosError | None:
114
+ """X's documented error answers as taxonomy errors, else ``None`` (conventions §5, §6).
115
+
116
+ The ``ClientConfig.classify`` hook: it sees every response before core's status
117
+ mapping. X answers an error as ``application/problem+json`` (the OpenAPI document's
118
+ ``Problem``: ``type``, ``title``, ``detail``) or as ``{"errors": [{"code",
119
+ "message"}]}`` (its ``Error``; the 429 of ``pages/rate-limits.md``, ``code: 88``);
120
+ the problem types are those of ``pages/response-codes-and-errors.md``, compared by
121
+ the URI's last segment. A 2xx is never an error here: a 200 that carries ``errors``
122
+ beside or instead of ``data`` is a partial answer the wrappers return as the page
123
+ (the page's "Partial errors").
124
+
125
+ - A ``usage-capped`` problem, at any 4xx status: ``RateLimitError`` with
126
+ ``retry_after`` ``BILLING_CYCLE``, since the cap holds until the next billing
127
+ cycle, whose start the answer does not give.
128
+ - A 429, or a ``rate-limit-exceeded`` problem at any 4xx: ``RateLimitError`` with
129
+ ``retry_after`` the seconds until ``x-rate-limit-reset`` (a Unix timestamp; never
130
+ negative), else ``RATE_LIMIT_WINDOW`` (900 s). Retries wait it out up to the
131
+ policy's ``backoff_max``; beyond that the error reaches the caller (ADR-0010).
132
+ - A 400, or an ``invalid-request`` problem at any 4xx: ``InvalidRequestError`` with
133
+ upstream's words, since the caller has to change the request (ADR-0007).
134
+ - A 404, or a ``resource-not-found`` problem at any 4xx: ``NotFoundError``.
135
+ - Everything else falls through to core's mapping: a 401 or 403 becomes
136
+ ``AuthError`` (the keyless and the wrong-key 401 answer ``Unauthorized``), a 5xx
137
+ ``UpstreamError``, retried.
138
+ """
139
+ status = response.status_code
140
+ if status < 400:
141
+ return None
142
+ payload = _payload(response)
143
+ kind = _problem_type(payload)
144
+ details = _details(payload)
145
+ said = f": {details}" if details else ""
146
+ where = _where(response)
147
+ if kind in _USAGE_CAPPED and status < 500:
148
+ return RateLimitError(
149
+ f"X usage cap reached (HTTP {status} from {where}){said}. Requests are blocked "
150
+ "until the next billing cycle; the Developer Console shows the cycle and the "
151
+ "spending limit.",
152
+ retry_after=BILLING_CYCLE,
153
+ source=SOURCE,
154
+ )
155
+ if status == 429 or (kind in _RATE_LIMITED and status < 500):
156
+ wait = _until_reset(response)
157
+ return RateLimitError(
158
+ f"X rate limit reached (HTTP {status} from {where}){said}. The endpoint's "
159
+ f"15-minute window resets in {wait:.0f} s.",
160
+ retry_after=wait,
161
+ source=SOURCE,
162
+ )
163
+ if status == 400 or (kind in _INVALID_REQUEST and status < 500):
164
+ return InvalidRequestError(
165
+ f"X refused the request (HTTP {status} from {where}){said}", source=SOURCE
166
+ )
167
+ if status == 404 or (kind in _NOT_FOUND and status < 500):
168
+ return NotFoundError(f"X found nothing (HTTP {status} from {where}){said}", source=SOURCE)
169
+ return None
170
+
171
+
172
+ config = ClientConfig(
173
+ source=SOURCE,
174
+ version=__version__,
175
+ base_url=BASE_URL,
176
+ rate_limit=RATE_LIMIT,
177
+ classify=classify,
178
+ )
179
+
180
+ # No QuotaPolicy (Johannes, 2026-10-29): one policy per client cannot track X's
181
+ # per-endpoint windows, so a 429 is answered by classify alone.
182
+
183
+ # The key is read from the environment on the first request, never at import.
184
+ auth = BearerAuth(API_KEY_ENV, source=SOURCE)
185
+ client = AsyncClient(config, auth=auth)
186
+
187
+ __all__ = [
188
+ "API_KEY_ENV",
189
+ "BASE_URL",
190
+ "BILLING_CYCLE",
191
+ "RATE_LIMIT",
192
+ "RATE_LIMIT_WINDOW",
193
+ "SOURCE",
194
+ "auth",
195
+ "classify",
196
+ "client",
197
+ "config",
198
+ ]
xippios/x/_version.py ADDED
@@ -0,0 +1,10 @@
1
+ """Package version, read from the installed distribution metadata."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("xippios-x")
7
+ except PackageNotFoundError: # pragma: no cover - only in an unbuilt checkout
8
+ __version__ = "0.0.0"
9
+
10
+ __all__ = ["__version__"]
@@ -0,0 +1,32 @@
1
+ """Endpoint wrappers, layer 1: one async function per upstream operation (conventions §2).
2
+
3
+ ``/add-endpoint`` adds them. A module and its function carry the OpenAPI document's
4
+ ``operationId`` in snake case (``getUsersByUsernames`` is ``get_users_by_usernames`` in
5
+ ``get_users_by_usernames.py``); the verbatim id stays in the first line of each wrapper's
6
+ docstring and in the ``endpoint=`` it passes. Each returns one answer, one page, as the
7
+ document's response model; paging is the caller's: a task returns one page and its token.
8
+ ``_query`` turns the parameters into the text X takes and refuses values outside the
9
+ document's bounds.
10
+ """
11
+
12
+ from xippios.x.api.get_lists_members import get_lists_members
13
+ from xippios.x.api.get_lists_posts import get_lists_posts
14
+ from xippios.x.api.get_posts_by_ids import get_posts_by_ids
15
+ from xippios.x.api.get_posts_counts_all import get_posts_counts_all
16
+ from xippios.x.api.get_posts_counts_recent import get_posts_counts_recent
17
+ from xippios.x.api.get_usage import get_usage
18
+ from xippios.x.api.get_users_by_usernames import get_users_by_usernames
19
+ from xippios.x.api.get_users_posts import get_users_posts
20
+ from xippios.x.api.search_posts_recent import search_posts_recent
21
+
22
+ __all__ = [
23
+ "get_lists_members",
24
+ "get_lists_posts",
25
+ "get_posts_by_ids",
26
+ "get_posts_counts_all",
27
+ "get_posts_counts_recent",
28
+ "get_usage",
29
+ "get_users_by_usernames",
30
+ "get_users_posts",
31
+ "search_posts_recent",
32
+ ]
@@ -0,0 +1,135 @@
1
+ """Query values as the wrappers send them, checked against the OpenAPI document's bounds.
2
+
3
+ Each helper turns one parameter into the text X takes (a list comma-separated, as the
4
+ document's ``style: form`` with ``explode: false`` has it; a time in RFC 3339 with
5
+ ``Z``) and refuses, before any request, a value outside the bounds the document gives
6
+ the parameter (``minItems``, ``maxItems``, ``pattern``, ``enum``, ``uniqueItems``,
7
+ ``minimum``, ``maximum``, ``minLength``, ``maxLength``), or two parameters given where the
8
+ document allows "at most one of" them, with ``InvalidRequestError`` naming the parameter
9
+ (conventions §5).
10
+ """
11
+
12
+ import re
13
+ from collections.abc import Sequence
14
+ from datetime import UTC, datetime
15
+ from enum import StrEnum
16
+
17
+ from xippios.core import InvalidRequestError
18
+
19
+ from xippios.x._client import SOURCE
20
+
21
+ __all__ = ["at_most_one", "bounded", "chosen", "instant", "listed", "matching", "text"]
22
+
23
+
24
+ def _refuse(message: str) -> InvalidRequestError:
25
+ return InvalidRequestError(message, source=SOURCE)
26
+
27
+
28
+ def listed(name: str, values: Sequence[str], *, max_items: int, pattern: re.Pattern[str]) -> str:
29
+ """``values`` comma-separated: between 1 and ``max_items``, each matching ``pattern``.
30
+
31
+ Raises:
32
+ InvalidRequestError: ``values`` is one string, empty, too long, or holds a value
33
+ that does not match.
34
+ """
35
+ if isinstance(values, str):
36
+ raise _refuse(f"{name} is a list of values, e.g. [{values!r}], not one string")
37
+ items = list(values)
38
+ if not 1 <= len(items) <= max_items:
39
+ raise _refuse(f"{name} takes 1 to {max_items} values, not {len(items)}")
40
+ wrong = [item for item in items if not pattern.fullmatch(item)]
41
+ if wrong:
42
+ raise _refuse(f"{name}: {wrong[0]!r} does not match {pattern.pattern}")
43
+ return ",".join(items)
44
+
45
+
46
+ def matching(name: str, value: str, pattern: re.Pattern[str]) -> str:
47
+ """``value`` when it is a string matching ``pattern``, e.g. a User id for the path.
48
+
49
+ Raises:
50
+ InvalidRequestError: ``value`` is not a string or does not match.
51
+ """
52
+ if not isinstance(value, str) or not pattern.fullmatch(value):
53
+ raise _refuse(f"{name}: {value!r} does not match {pattern.pattern}")
54
+ return value
55
+
56
+
57
+ def chosen[E: StrEnum](name: str, values: Sequence[E], kind: type[E]) -> str:
58
+ """``values``, members of ``kind``, comma-separated: at least one, none twice.
59
+
60
+ Raises:
61
+ InvalidRequestError: ``values`` is one string, empty, repeats a value, or holds
62
+ one ``kind`` does not have; the message lists the valid values.
63
+ """
64
+ if isinstance(values, str):
65
+ raise _refuse(f"{name} is a list of values, e.g. [{values!r}], not one string")
66
+ items: list[str] = []
67
+ for value in values:
68
+ try:
69
+ member = kind(value)
70
+ except ValueError:
71
+ valid = ", ".join(member.value for member in kind)
72
+ raise _refuse(f"{name}: {value!r} is not one of {valid}") from None
73
+ if member.value in items:
74
+ raise _refuse(f"{name}: {member.value!r} is given twice")
75
+ items.append(member.value)
76
+ if not items:
77
+ raise _refuse(f"{name} takes at least one value")
78
+ return ",".join(items)
79
+
80
+
81
+ def bounded(name: str, value: int, *, low: int, high: int) -> str:
82
+ """``value`` as text, when it lies between ``low`` and ``high``.
83
+
84
+ Raises:
85
+ InvalidRequestError: ``value`` is not an integer in that range.
86
+ """
87
+ if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
88
+ raise _refuse(f"{name} takes an integer from {low} to {high}, not {value!r}")
89
+ return str(value)
90
+
91
+
92
+ def text(name: str, value: str, *, max_length: int | None = None) -> str:
93
+ """``value`` when it is a non-empty string, at most ``max_length`` characters.
94
+
95
+ Raises:
96
+ InvalidRequestError: ``value`` is empty or too long.
97
+ """
98
+ if not isinstance(value, str) or not value:
99
+ raise _refuse(f"{name} takes a non-empty string")
100
+ if max_length is not None and len(value) > max_length:
101
+ raise _refuse(f"{name} takes at most {max_length} characters, not {len(value)}")
102
+ return value
103
+
104
+
105
+ def instant(name: str, value: datetime) -> str:
106
+ """``value`` in UTC as RFC 3339 with ``Z``, e.g. ``2026-07-31T00:00:00Z``.
107
+
108
+ Seconds when the time has no fraction of a second, else milliseconds
109
+ (``2026-07-31T00:00:00.250Z``), the precision of X's own times.
110
+
111
+ Raises:
112
+ InvalidRequestError: ``value`` is not a datetime with a zone.
113
+ """
114
+ if not isinstance(value, datetime) or value.utcoffset() is None:
115
+ raise _refuse(
116
+ f"{name} takes a datetime with a zone, e.g. datetime(2026, 7, 31, tzinfo=UTC)"
117
+ )
118
+ moment = value.astimezone(UTC)
119
+ if moment.microsecond:
120
+ return moment.isoformat(timespec="milliseconds").replace("+00:00", "Z")
121
+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
122
+
123
+
124
+ def at_most_one(**given: object) -> None:
125
+ """Refuse two of ``given`` set where the document says "At most one of" them.
126
+
127
+ E.g. ``at_most_one(next_token=..., pagination_token=...)``: the description of
128
+ ``searchPostsRecent``, ``getPostsCountsRecent`` and ``getPostsCountsAll`` says "At most
129
+ one of ``pagination_token``, ``next_token`` may be provided".
130
+
131
+ Raises:
132
+ InvalidRequestError: More than one of ``given`` is not ``None``.
133
+ """
134
+ if sum(value is not None for value in given.values()) > 1:
135
+ raise _refuse(f"give {' or '.join(given)}, not both: at most one may be provided")
@@ -0,0 +1,80 @@
1
+ """``GET /2/lists/{id}/members``, operation ``getListsMembers``: one page of a List's members.
2
+
3
+ Reference: ``docs/upstream/openapi/openapi.json``, ``paths./2/lists/{id}/members.get``:
4
+ ``id`` (``ListId``, ``^[0-9]{1,19}$``), ``max_results`` (1 to 100, 100 when omitted),
5
+ ``pagination_token`` ("A 64-bit signed integer.", a string the document does not bound,
6
+ sent as given), ``user.fields``, ``expansions`` (the ``UserExpansionsParameter``) and
7
+ ``post.fields``; the answer ``GetListsMembersResponse``: ``data`` (``User``), ``includes``,
8
+ ``errors``, ``meta`` (``result_count``, ``next_token``, ``previous_token``). Paging is the
9
+ caller's: a task returns one page and its token.
10
+
11
+ Recorded on 2026-10-29 from a List @XDevelopers owns (``xdevelopers_list_ten``): its eight
12
+ members for ``max_results=10``, ``meta.result_count`` 8 and no ``next_token``; without
13
+ ``post.fields`` X answers a member's metrics in the guides' spelling (``tweet_count``),
14
+ which ``UserPublicMetrics`` reads as ``post_count``. Price: 0.010 USD a User returned,
15
+ 0.005 USD a Post in ``includes`` (``pages/pricing.md``); X reported
16
+ ``x-rate-limit-limit: 900``, as ``pages/rate-limits.md`` lists.
17
+ """
18
+
19
+ import re
20
+ from collections.abc import Sequence
21
+
22
+ from xippios.core import parse
23
+
24
+ from xippios.x._client import SOURCE, client
25
+ from xippios.x.api._query import bounded, chosen, matching
26
+ from xippios.x.models import GetListsMembersResponse, PostField, UserExpansion, UserField
27
+
28
+ __all__ = ["get_lists_members"]
29
+
30
+ _LIST_ID = re.compile(r"[0-9]{1,19}")
31
+
32
+
33
+ async def get_lists_members(
34
+ id: str,
35
+ *,
36
+ max_results: int | None = None,
37
+ pagination_token: str | None = None,
38
+ user_fields: Sequence[UserField] | None = None,
39
+ expansions: Sequence[UserExpansion] | None = None,
40
+ post_fields: Sequence[PostField] | None = None,
41
+ ) -> GetListsMembersResponse:
42
+ """``getListsMembers``: one page of the X users who are members of a List.
43
+
44
+ Args:
45
+ id: ``id``, the List's id of up to 19 digits, e.g. ``"715919216927322112"`` (a
46
+ List of @XDevelopers').
47
+ max_results: ``max_results``, Users per page from 1 to 100, e.g. ``10``; X's
48
+ default, 100, when omitted.
49
+ pagination_token: ``pagination_token``, the ``meta.next_token`` of the page
50
+ before, sent as given.
51
+ user_fields: ``user.fields``, the User fields to return beyond ``id``, ``name``
52
+ and ``username``, e.g. ``[UserField.CREATED_AT, UserField.PUBLIC_METRICS]``.
53
+ expansions: ``expansions``, e.g. ``[UserExpansion.MOST_RECENT_POST_ID]``, which
54
+ puts each member's most recent Post into ``includes``.
55
+ post_fields: ``post.fields``, the fields of the Posts in ``includes``, e.g.
56
+ ``[PostField.CREATED_AT, PostField.LANG]``.
57
+
58
+ Returns:
59
+ One page: the members in ``data``, ``meta.next_token`` for the next page.
60
+
61
+ Raises:
62
+ InvalidRequestError: A value outside the document's bounds, refused before the
63
+ call, or X's HTTP 400.
64
+ AuthError: X refused the key in ``X_API_KEY`` (HTTP 401).
65
+ RateLimitError: The operation's 15-minute window is spent, ``retry_after`` set.
66
+ """
67
+ params: dict[str, str] = {}
68
+ if max_results is not None:
69
+ params["max_results"] = bounded("max_results", max_results, low=1, high=100)
70
+ if pagination_token is not None:
71
+ params["pagination_token"] = pagination_token
72
+ if user_fields is not None:
73
+ params["user.fields"] = chosen("user.fields", user_fields, UserField)
74
+ if expansions is not None:
75
+ params["expansions"] = chosen("expansions", expansions, UserExpansion)
76
+ if post_fields is not None:
77
+ params["post.fields"] = chosen("post.fields", post_fields, PostField)
78
+ path = f"/lists/{matching('id', id, _LIST_ID)}/members"
79
+ raw = await client.get_json(path, params=params)
80
+ return parse(GetListsMembersResponse, raw, source=SOURCE, endpoint="getListsMembers")
@@ -0,0 +1,84 @@
1
+ """``GET /2/lists/{id}/tweets``, operation ``getListsPosts``: one page of a List's Posts.
2
+
3
+ Reference: ``docs/upstream/openapi/openapi.json``, ``paths./2/lists/{id}/tweets.get``:
4
+ ``id`` (``ListId``, ``^[0-9]{1,19}$``), ``max_results`` (1 to 100, 100 when omitted),
5
+ ``pagination_token`` ("A base32hex-encoded pagination token", at least one character),
6
+ ``post.fields``, ``expansions`` and ``user.fields``; the answer ``GetListsPostsResponse``:
7
+ ``data``, ``includes``, ``errors``, ``meta`` (``result_count``, ``next_token``,
8
+ ``previous_token``). The Posts are those of the List's members. The document's
9
+ ``media.fields``, ``poll.fields`` and ``place.fields`` are not wrapped: no task needs them
10
+ yet, and their objects stay as sent in ``includes``. Paging is the caller's: a task
11
+ returns one page and its token.
12
+
13
+ Recorded on 2026-10-29 from a List @XDevelopers owns (``xdevelopers_list_ten``): nine Posts
14
+ for ``max_results=10``, newest first, with a ``next_token`` (fewer than ``max_results``
15
+ while more exist, as ``pages/pagination.md`` says) and no ``newest_id`` or ``oldest_id``,
16
+ which the document's ``meta`` does not have either. A List id X does not find is answered
17
+ with HTTP 200, a ``resource-not-found`` problem in ``errors`` and no ``data``
18
+ (``unknown_id``), which the wrapper returns as the page. Price: 0.005 USD a Post returned
19
+ (``pages/pricing.md``); X reported ``x-rate-limit-limit: 900``, as ``pages/rate-limits.md``
20
+ lists.
21
+ """
22
+
23
+ import re
24
+ from collections.abc import Sequence
25
+
26
+ from xippios.core import parse
27
+
28
+ from xippios.x._client import SOURCE, client
29
+ from xippios.x.api._query import bounded, chosen, matching, text
30
+ from xippios.x.models import GetListsPostsResponse, PostExpansion, PostField, UserField
31
+
32
+ __all__ = ["get_lists_posts"]
33
+
34
+ _LIST_ID = re.compile(r"[0-9]{1,19}")
35
+
36
+
37
+ async def get_lists_posts(
38
+ id: str,
39
+ *,
40
+ max_results: int | None = None,
41
+ pagination_token: str | None = None,
42
+ post_fields: Sequence[PostField] | None = None,
43
+ expansions: Sequence[PostExpansion] | None = None,
44
+ user_fields: Sequence[UserField] | None = None,
45
+ ) -> GetListsPostsResponse:
46
+ """``getListsPosts``: one page of the posts of an X List's members, newest first.
47
+
48
+ Args:
49
+ id: ``id``, the List's id of up to 19 digits, e.g. ``"715919216927322112"`` (a
50
+ List of @XDevelopers').
51
+ max_results: ``max_results``, Posts per page from 1 to 100, e.g. ``10``; X's
52
+ default, 100, when omitted.
53
+ pagination_token: ``pagination_token``, the ``meta.next_token`` of the page before,
54
+ as X sent it.
55
+ post_fields: ``post.fields``, e.g. ``[PostField.CREATED_AT, PostField.LANG,
56
+ PostField.PUBLIC_METRICS, PostField.CONVERSATION_ID]``.
57
+ expansions: ``expansions``, e.g. ``[PostExpansion.AUTHOR_ID]``, which puts each
58
+ Post's author into ``includes``.
59
+ user_fields: ``user.fields``, the fields of the Users in ``includes``, e.g.
60
+ ``[UserField.CREATED_AT]``.
61
+
62
+ Returns:
63
+ One page: the Posts in ``data``, ``meta.next_token`` for the next page.
64
+
65
+ Raises:
66
+ InvalidRequestError: A value outside the document's bounds, refused before the
67
+ call, or X's HTTP 400.
68
+ AuthError: X refused the key in ``X_API_KEY`` (HTTP 401).
69
+ RateLimitError: The operation's 15-minute window is spent, ``retry_after`` set.
70
+ """
71
+ params: dict[str, str] = {}
72
+ if max_results is not None:
73
+ params["max_results"] = bounded("max_results", max_results, low=1, high=100)
74
+ if pagination_token is not None:
75
+ params["pagination_token"] = text("pagination_token", pagination_token)
76
+ if post_fields is not None:
77
+ params["post.fields"] = chosen("post.fields", post_fields, PostField)
78
+ if expansions is not None:
79
+ params["expansions"] = chosen("expansions", expansions, PostExpansion)
80
+ if user_fields is not None:
81
+ params["user.fields"] = chosen("user.fields", user_fields, UserField)
82
+ path = f"/lists/{matching('id', id, _LIST_ID)}/tweets"
83
+ raw = await client.get_json(path, params=params)
84
+ return parse(GetListsPostsResponse, raw, source=SOURCE, endpoint="getListsPosts")
@@ -0,0 +1,72 @@
1
+ """``GET /2/tweets``, operation ``getPostsByIds``: Posts by their ids.
2
+
3
+ Reference: ``docs/upstream/openapi/openapi.json``, ``paths./2/tweets.get``: ``ids`` (1 to
4
+ 100, each ``^[0-9]{1,19}$``), ``post.fields``, ``expansions`` (the
5
+ ``PostExpansionsParameter``) and ``user.fields``, every list comma-separated; the answer
6
+ ``GetPostsByIdsResponse``: ``data``, ``includes``, ``errors``, ``meta.result_count``. An id
7
+ X does not find is a ``Problem`` in ``errors``, in an HTTP 200. The document's
8
+ ``media.fields``, ``poll.fields`` and ``place.fields`` are not wrapped: no task needs them
9
+ yet, and their objects stay as sent in ``includes``.
10
+
11
+ Wire names, recorded on 2026-10-29 (``most_recent_three``): X takes the document's
12
+ ``post.fields`` and answers in the document's names (``edit_history_post_ids``,
13
+ ``repost_count``), where the guides write ``tweet.fields``. It took
14
+ ``expansions=referenced_posts`` too (HTTP 200) and answered ``referenced_posts`` and
15
+ ``includes.posts``, where the guides write ``referenced_tweets.id`` and
16
+ ``referenced_tweets``, in the case's first recording, replaced the same day without the
17
+ expansion (``CLAUDE.md``, Recording fixtures). Price: 0.005 USD a Post returned, in
18
+ ``data`` or ``includes`` (``pages/pricing.md``).
19
+ """
20
+
21
+ import re
22
+ from collections.abc import Sequence
23
+
24
+ from xippios.core import parse
25
+
26
+ from xippios.x._client import SOURCE, client
27
+ from xippios.x.api._query import chosen, listed
28
+ from xippios.x.models import GetPostsByIdsResponse, PostExpansion, PostField, UserField
29
+
30
+ __all__ = ["get_posts_by_ids"]
31
+
32
+ _ID = re.compile(r"[0-9]{1,19}")
33
+
34
+
35
+ async def get_posts_by_ids(
36
+ ids: Sequence[str],
37
+ *,
38
+ post_fields: Sequence[PostField] | None = None,
39
+ expansions: Sequence[PostExpansion] | None = None,
40
+ user_fields: Sequence[UserField] | None = None,
41
+ ) -> GetPostsByIdsResponse:
42
+ """``getPostsByIds``: look up to 100 X posts by id, one answer.
43
+
44
+ Args:
45
+ ids: ``ids``, 1 to 100 Post ids of up to 19 digits, e.g.
46
+ ``["2115806101480337475"]``.
47
+ post_fields: ``post.fields``, the Post fields to return beyond ``id`` and
48
+ ``text``, e.g. ``[PostField.CREATED_AT, PostField.PUBLIC_METRICS]``.
49
+ expansions: ``expansions``, e.g. ``[PostExpansion.REFERENCED_POSTS]``, which puts
50
+ the reposted, quoted or replied-to Posts into ``includes``.
51
+ user_fields: ``user.fields``, the fields of the Users in ``includes`` (with
52
+ ``PostExpansion.AUTHOR_ID``), e.g. ``[UserField.CREATED_AT]``.
53
+
54
+ Returns:
55
+ The answer: the Posts found in ``data``, the expanded objects in ``includes``, a
56
+ ``Problem`` for each id not found in ``errors``, ``meta.result_count``.
57
+
58
+ Raises:
59
+ InvalidRequestError: A value outside the document's bounds, refused before the
60
+ call, or X's HTTP 400.
61
+ AuthError: X refused the key in ``X_API_KEY`` (HTTP 401).
62
+ RateLimitError: The operation's 15-minute window is spent, ``retry_after`` set.
63
+ """
64
+ params = {"ids": listed("ids", ids, max_items=100, pattern=_ID)}
65
+ if post_fields is not None:
66
+ params["post.fields"] = chosen("post.fields", post_fields, PostField)
67
+ if expansions is not None:
68
+ params["expansions"] = chosen("expansions", expansions, PostExpansion)
69
+ if user_fields is not None:
70
+ params["user.fields"] = chosen("user.fields", user_fields, UserField)
71
+ raw = await client.get_json("/tweets", params=params)
72
+ return parse(GetPostsByIdsResponse, raw, source=SOURCE, endpoint="getPostsByIds")