HTTP Client API Reference¶
Complete API reference for HTTP clients.
Base Interface¶
HttpClient ¶
Bases: ABC
Abstract base class for HTTP clients.
This is the unified HTTP client interface for the stkai SDK. All HTTP operations in the SDK should use this interface.
Implementations handle authentication and can be wrapped with decorators for rate limiting, retries, and other cross-cutting concerns.
Example
class MyHttpClient(HttpClient): ... def get(self, url, headers=None, timeout=30): ... return requests.get(url, headers=headers, timeout=timeout) ... def post(self, url, data=None, headers=None, timeout=30): ... return requests.post(url, json=data, headers=headers, timeout=timeout)
Source code in src/stkai/_http.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
Functions¶
get
abstractmethod
¶
Execute an authenticated GET request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
headers
|
dict[str, str] | None
|
Additional headers to include (merged with auth headers). |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
RequestException
|
If the HTTP request fails. |
Source code in src/stkai/_http.py
post
abstractmethod
¶
post(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Execute an authenticated POST request with JSON body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include (merged with auth headers). |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
RequestException
|
If the HTTP request fails. |
Source code in src/stkai/_http.py
post_stream ¶
post_stream(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Execute an authenticated POST request with streaming response.
The returned response has stream=True, meaning the body is NOT
pre-downloaded. The caller MUST iterate and close the response.
This is a separate method from post() because a streaming response
behaves fundamentally differently — the body must be iterated and the
connection explicitly closed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include (merged with auth headers). |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response with stream=True. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the implementation does not support streaming. |
RequestException
|
If the HTTP request fails. |
Source code in src/stkai/_http.py
Implementations¶
StkCLIHttpClient ¶
Bases: HttpClient
HTTP client using StackSpot CLI (oscli) for authentication.
This client delegates authentication to the StackSpot CLI, which must be installed and logged in for this client to work.
The CLI handles token management, refresh, and injection of authorization headers into HTTP requests.
Note
Requires the oscli package to be installed and configured.
Install via: pip install oscli
Login via: stk login
Example
from stkai._http import StkCLIHttpClient client = StkCLIHttpClient() response = client.post("https://api.example.com/endpoint", data={"key": "value"})
See Also
StandaloneHttpClient: Alternative that doesn't require oscli.
Source code in src/stkai/_http.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
Functions¶
get ¶
Execute an authenticated GET request using oscli.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If url is empty or timeout is invalid. |
RequestException
|
If the HTTP request fails. |
Source code in src/stkai/_http.py
post ¶
post(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Execute an authenticated POST request using oscli.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If url is empty or timeout is invalid. |
RequestException
|
If the HTTP request fails. |
Source code in src/stkai/_http.py
post_stream ¶
post_stream(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Execute an authenticated streaming POST request using oscli.
Delegates to oscli's post_with_authorization with stream=True
passed via kwargs (forwarded to requests.post).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response with stream=True. |
Source code in src/stkai/_http.py
StandaloneHttpClient ¶
Bases: HttpClient
HTTP client using AuthProvider for standalone authentication.
This client uses an AuthProvider to obtain authorization tokens, enabling standalone operation without the StackSpot CLI.
Use this client when: - You want to run without the StackSpot CLI dependency - You need to use client credentials directly - You're deploying to an environment without CLI access
Example
from stkai._auth import ClientCredentialsAuthProvider from stkai._http import StandaloneHttpClient
auth = ClientCredentialsAuthProvider( ... client_id="my-client-id", ... client_secret="my-client-secret", ... ) client = StandaloneHttpClient(auth_provider=auth) response = client.post("https://api.example.com/endpoint", data={"key": "value"})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth_provider
|
AuthProvider
|
Provider for authorization tokens. |
required |
See Also
ClientCredentialsAuthProvider: OAuth2 client credentials implementation. StkCLIHttpClient: Alternative that uses oscli for authentication.
Source code in src/stkai/_http.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
Functions¶
__init__ ¶
Initialize the standalone HTTP client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth_provider
|
AuthProvider
|
Provider for authorization tokens. |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If auth_provider is None or invalid type. |
Source code in src/stkai/_http.py
get ¶
Execute an authenticated GET request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If url is empty or timeout is invalid. |
RequestException
|
If the HTTP request fails. |
AuthenticationError
|
If unable to obtain authorization token. |
Source code in src/stkai/_http.py
post ¶
post(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Execute an authenticated POST request with JSON body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If url is empty or timeout is invalid. |
RequestException
|
If the HTTP request fails. |
AuthenticationError
|
If unable to obtain authorization token. |
Source code in src/stkai/_http.py
post_stream ¶
post_stream(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Execute an authenticated streaming POST request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response with stream=True. |
Source code in src/stkai/_http.py
EnvironmentAwareHttpClient ¶
Bases: HttpClient
Environment-aware HTTP client that automatically selects the appropriate implementation.
This client detects the runtime environment and lazily creates the appropriate HTTP client implementation:
- If StackSpot CLI (oscli) is installed → uses StkCLIHttpClient
- If credentials are configured → uses StandaloneHttpClient
- Otherwise → raises ValueError with clear instructions
The detection happens lazily on the first request, allowing configuration
via STKAI.configure() after import.
This implementation is thread-safe using double-checked locking pattern.
Example
from stkai._http import EnvironmentAwareHttpClient client = EnvironmentAwareHttpClient()
Automatically uses CLI or standalone based on environment¶
response = client.post("https://api.example.com/endpoint", data={"key": "value"})
Note
CLI takes precedence over credentials if both are available.
See Also
StkCLIHttpClient: Explicit CLI-based client. StandaloneHttpClient: Explicit standalone client.
Source code in src/stkai/_http.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 | |
Functions¶
__init__ ¶
get ¶
Delegate GET request to the appropriate HTTP client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Source code in src/stkai/_http.py
post ¶
post(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Delegate POST request to the appropriate HTTP client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Source code in src/stkai/_http.py
post_stream ¶
post_stream(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Delegate streaming POST request to the appropriate HTTP client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response with stream=True. |
Source code in src/stkai/_http.py
Rate Limiting¶
TokenBucketRateLimitedHttpClient ¶
Bases: HttpClient
HTTP client decorator that applies rate limiting to requests.
Uses the Token Bucket algorithm to limit the rate of requests. Only POST requests are rate-limited; GET requests (typically polling) pass through without limiting.
This decorator is thread-safe and can be used with concurrent requests.
Example
from stkai._rate_limit import TokenBucketRateLimitedHttpClient from stkai._http import StkCLIHttpClient
Limit to 10 requests per minute, give up after 45s waiting¶
client = TokenBucketRateLimitedHttpClient( ... delegate=StkCLIHttpClient(), ... max_requests=10, ... time_window=60.0, ... max_wait_time=45.0, ... )
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
HttpClient
|
The underlying HTTP client to delegate requests to. |
required |
max_requests
|
int
|
Maximum number of requests allowed in the time window. |
required |
time_window
|
float
|
Time window in seconds for the rate limit. |
required |
max_wait_time
|
float | None
|
Maximum time in seconds to wait for a token. If None, waits indefinitely. Default is 45 seconds. |
45.0
|
Raises:
| Type | Description |
|---|---|
TokenAcquisitionTimeoutError
|
If max_wait_time is exceeded while waiting for a token. |
Source code in src/stkai/_rate_limit.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 | |
Functions¶
__init__ ¶
__init__(delegate: HttpClient, max_requests: int, time_window: float, max_wait_time: float | None = 45.0)
Initialize the rate-limited HTTP client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
HttpClient
|
The underlying HTTP client to delegate requests to. |
required |
max_requests
|
int
|
Maximum number of requests allowed in the time window. |
required |
time_window
|
float
|
Time window in seconds for the rate limit. |
required |
max_wait_time
|
float | None
|
Maximum time in seconds to wait for a token. If None, waits indefinitely. Default is 30 seconds. |
45.0
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any parameter is invalid. |
Source code in src/stkai/_rate_limit.py
get ¶
Delegate GET request without rate limiting.
GET requests (typically polling) are not rate-limited as they usually don't count against API rate limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Source code in src/stkai/_rate_limit.py
post ¶
post(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Acquire a rate limit token, then delegate POST request.
This method blocks until a token is available if the rate limit has been reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Source code in src/stkai/_rate_limit.py
post_stream ¶
post_stream(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Acquire a rate limit token, then delegate streaming POST request.
Source code in src/stkai/_rate_limit.py
AdaptiveRateLimitedHttpClient ¶
Bases: HttpClient
HTTP client decorator with adaptive rate limiting using AIMD algorithm.
Extends rate limiting with: - AIMD algorithm to adapt rate based on server responses - Floor protection to prevent deadlock - Configurable timeout to prevent indefinite blocking
When an HTTP 429 response is received, this client: 1. Applies AIMD penalty (reduces effective rate) 2. Raises requests.HTTPError for the caller/Retrying to handle
This follows the pattern of Resilience4J, Polly, and AWS SDK where rate limiting and retry are separate concerns. Use this client with Retrying for complete 429 handling with backoff.
Example
from stkai._rate_limit import AdaptiveRateLimitedHttpClient from stkai._http import StkCLIHttpClient client = AdaptiveRateLimitedHttpClient( ... delegate=StkCLIHttpClient(), ... max_requests=100, ... time_window=60.0, ... min_rate_floor=0.1, # Never below 10 req/min ... max_wait_time=45.0, # Give up after 45s waiting ... )
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
HttpClient
|
The underlying HTTP client to delegate requests to. |
required |
max_requests
|
int
|
Maximum number of requests allowed in the time window. |
required |
time_window
|
float
|
Time window in seconds for the rate limit. |
required |
min_rate_floor
|
float
|
Minimum rate as fraction of max_requests (default: 0.1 = 10%). |
0.1
|
penalty_factor
|
float
|
Rate reduction factor on 429 (default: 0.3 = -30%). |
0.3
|
recovery_factor
|
float
|
Rate increase factor on success (default: 0.05 = +5%). |
0.05
|
max_wait_time
|
float | None
|
Maximum time in seconds to wait for a token. If None, waits indefinitely. Default is 45 seconds. |
45.0
|
Raises:
| Type | Description |
|---|---|
TokenAcquisitionTimeoutError
|
If max_wait_time is exceeded while waiting for a token. |
HTTPError
|
When server returns HTTP 429 (after AIMD penalty applied). |
Source code in src/stkai/_rate_limit.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 | |
Functions¶
__init__ ¶
__init__(delegate: HttpClient, max_requests: int, time_window: float, min_rate_floor: float = 0.1, penalty_factor: float = 0.3, recovery_factor: float = 0.05, max_wait_time: float | None = 45.0)
Initialize the adaptive rate-limited HTTP client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
HttpClient
|
The underlying HTTP client to delegate requests to. |
required |
max_requests
|
int
|
Maximum number of requests allowed in the time window. |
required |
time_window
|
float
|
Time window in seconds for the rate limit. |
required |
min_rate_floor
|
float
|
Minimum rate as fraction of max_requests (default: 0.1 = 10%). |
0.1
|
penalty_factor
|
float
|
Rate reduction factor on 429 (default: 0.3 = -30%). |
0.3
|
recovery_factor
|
float
|
Rate increase factor on success (default: 0.05 = +5%). |
0.05
|
max_wait_time
|
float | None
|
Maximum time in seconds to wait for a token. If None, waits indefinitely. Default is 30 seconds. |
45.0
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any parameter is invalid. |
Source code in src/stkai/_rate_limit.py
get ¶
Delegate GET request without rate limiting.
GET requests (typically polling) are not rate-limited as they usually don't count against API rate limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Source code in src/stkai/_rate_limit.py
post ¶
post(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Acquire token, delegate request, adapt rate based on response.
This method: 1. Acquires a rate limit token (blocking if necessary) 2. Delegates the request to the underlying client 3. On success: gradually increases the effective rate (AIMD recovery) 4. On 429: reduces effective rate (AIMD penalty) and raises HTTPError
The 429 handling follows the separation of concerns pattern: - Rate limiter: applies AIMD penalty and raises exception - Retrying: handles retry with Retry-After header support
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The full URL to request. |
required |
data
|
dict[str, Any] | None
|
JSON-serializable data to send in the request body. |
None
|
headers
|
dict[str, str] | None
|
Additional headers to include. |
None
|
timeout
|
int
|
Request timeout in seconds. |
30
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response (non-429 responses only). |
Raises:
| Type | Description |
|---|---|
ServerSideRateLimitError
|
When server returns HTTP 429. |
TokenAcquisitionTimeoutError
|
When max_wait_time is exceeded. |
Source code in src/stkai/_rate_limit.py
post_stream ¶
post_stream(url: str, data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: int = 30) -> requests.Response
Acquire token, delegate streaming POST, adapt rate based on response.
Source code in src/stkai/_rate_limit.py
Exceptions¶
ClientSideRateLimitError ¶
Bases: RetryableError
Base exception for client-side rate limiting errors.
This is the base class for all rate limiting errors that originate from the client's rate limiter (TokenBucket, Adaptive, etc.), as opposed to server-side rate limiting (HTTP 429).
Extends RetryableError so all client-side rate limit errors are automatically retried by the Retrying context manager.
Example
try: ... client.post(url, data) ... except ClientSideRateLimitError as e: ... print(f"Client-side rate limit: {e}")
Source code in src/stkai/_rate_limit.py
TokenAcquisitionTimeoutError ¶
Bases: ClientSideRateLimitError
Raised when rate limiter exceeds max_wait_time waiting for a token.
This exception indicates that a thread waited too long to acquire a rate limit token and gave up. This prevents threads from blocking indefinitely when rate limits are very restrictive.
Extends ClientSideRateLimitError (which extends RetryableError) so it's automatically retried by the Retrying context manager, following the pattern used by Resilience4J, Polly, failsafe-go, AWS SDK, and Spring Retry - where rate limit/throttling exceptions are retryable by default.
Attributes:
| Name | Type | Description |
|---|---|---|
waited |
Time in seconds the thread waited before giving up. |
|
max_wait_time |
The configured maximum wait time. |
Example
try: ... client.post(url, data) ... except TokenAcquisitionTimeoutError as e: ... print(f"Rate limit timeout after {e.waited:.1f}s")
Source code in src/stkai/_rate_limit.py
ServerSideRateLimitError ¶
Bases: RetryableError
Raised when server returns HTTP 429 (Too Many Requests).
This exception indicates that the server has rate-limited the request. It wraps the original response so the Retry-After header can be extracted for calculating the appropriate wait time before retrying.
Extends RetryableError so it's automatically retried by the Retrying context manager. The Retrying class will extract the Retry-After header from the wrapped response to determine the wait time.
Only raised by AdaptiveRateLimitedHttpClient after applying AIMD penalty. Other clients (TokenBucket, no rate-limit) let HTTPError propagate directly.
Attributes:
| Name | Type | Description |
|---|---|---|
response |
The original HTTP response with status code 429. |
Example
try: ... client.post(url, data) ... except ServerSideRateLimitError as e: ... retry_after = e.response.headers.get("Retry-After") ... print(f"Server rate limited. Retry after: {retry_after}s")
Source code in src/stkai/_rate_limit.py
Authentication¶
AuthProvider ¶
Bases: ABC
Abstract base class for authentication providers.
Implementations are responsible for obtaining and managing access tokens. All implementations must be thread-safe.
Example
class MyAuthProvider(AuthProvider): ... def get_access_token(self) -> str: ... return "my-token" ... auth = MyAuthProvider() headers = auth.get_auth_headers()
{"Authorization": "Bearer my-token"}¶
Source code in src/stkai/_auth.py
Functions¶
get_access_token
abstractmethod
¶
Obtain a valid access token.
Returns:
| Type | Description |
|---|---|
str
|
Access token string (without "Bearer" prefix). |
Raises:
| Type | Description |
|---|---|
AuthenticationError
|
If unable to obtain a valid token. |
get_auth_headers ¶
Return authorization headers for HTTP requests.
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dict with Authorization header containing Bearer token. |
Example
headers = auth.get_auth_headers()
{"Authorization": "Bearer eyJ..."}¶
Source code in src/stkai/_auth.py
ClientCredentialsAuthProvider ¶
Bases: AuthProvider
OAuth2 Client Credentials flow for StackSpot.
This provider implements the OAuth2 client credentials grant type, which is used for machine-to-machine authentication.
Features
- Token caching: Avoids unnecessary token requests.
- Auto-refresh: Automatically refreshes tokens before expiration.
- Thread-safe: Safe for use across multiple threads.
Attributes:
| Name | Type | Description |
|---|---|---|
DEFAULT_TOKEN_URL |
Default StackSpot OAuth2 token endpoint. |
|
DEFAULT_REFRESH_MARGIN |
Seconds before expiration to refresh (60s). |
Example
auth = ClientCredentialsAuthProvider( ... client_id="my-client-id", ... client_secret="my-client-secret", ... ) headers = auth.get_auth_headers()
{"Authorization": "Bearer eyJ..."}¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
StackSpot client ID. |
required |
client_secret
|
str
|
StackSpot client secret. |
required |
token_url
|
str
|
OAuth2 token endpoint URL. |
DEFAULT_TOKEN_URL
|
refresh_margin
|
int
|
Seconds before expiration to trigger refresh. |
DEFAULT_REFRESH_MARGIN
|
Source code in src/stkai/_auth.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
Functions¶
get_access_token ¶
Obtain a valid access token, fetching a new one if necessary.
This method is thread-safe. If the current token is valid (not expired and not within the refresh margin), it returns the cached token. Otherwise, it fetches a new token from the OAuth2 endpoint.
Returns:
| Type | Description |
|---|---|
str
|
Valid access token string. |
Raises:
| Type | Description |
|---|---|
AuthenticationError
|
If unable to obtain a valid token. |
Source code in src/stkai/_auth.py
AuthenticationError ¶
Bases: Exception
Raised when authentication fails.
This exception is raised when the authentication provider fails to obtain or refresh an access token.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
Description of the authentication failure. |
|
cause |
The underlying exception that caused the failure, if any. |
Example
try: ... token = auth.get_access_token() ... except AuthenticationError as e: ... print(f"Auth failed: {e}")
Source code in src/stkai/_auth.py
create_standalone_auth ¶
Create a ClientCredentialsAuthProvider from configuration.
This helper function creates an auth provider using credentials from the provided config or from the global STKAI.config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig | None
|
Optional AuthConfig with credentials. If None, uses STKAI.config.auth from global configuration. |
None
|
Returns:
| Type | Description |
|---|---|
ClientCredentialsAuthProvider
|
Configured ClientCredentialsAuthProvider instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If credentials are not configured. |
Example
from stkai import STKAI STKAI.configure(auth={"client_id": "x", "client_secret": "y"}) auth = create_standalone_auth()
Uses credentials from global config¶