Skip to content

Client

APIClient

Bases: Generic[A], APIMixin

The main class for interacting with the CTFd API

Parameters:

Name Type Description Default
url str | URL

The base URL of the CTFd instance

required
auth BaseAuthStrategy | str | None

The authentication strategy to use. If a string is provided, it is assumed to be a token. If None is provided, no authentication is used.

None
user_agent str

The user agent to use for requests, by default "CTFdPy/0.1.0"

'CTFdPy/0.1.0'
follow_redirects bool

Whether to follow redirects, by default False

False

Attributes:

Name Type Description
url URL

The base URL of the CTFd instance

auth BaseAuthStrategy

The authentication strategy to use

challenges ChallengesAPI

Interface for interacting with the /api/v1/challenges CTFd API endpoint.

files FilesAPI

Interface for interacting with the /api/v1/files CTFd API endpoint.

flags FlagsAPI

Interface for interacting with the /api/v1/flags CTFd API endpoint.

hints HintsAPI

Interface for interacting with the /api/v1/hints CTFd API endpoint.

tags TagsAPI

Interface for interacting with the /api/v1/tags CTFd API endpoint.

topics TopicsAPI

Interface for interacting with the /api/v1/topics CTFd API endpoint.

users UsersAPI

Interface for interacting with the /api/v1/users CTFd API endpoint.

Source code in ctfdpy\client.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 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
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
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
436
437
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
class APIClient(Generic[A], APIMixin):
    """
    The main class for interacting with the CTFd API

    Parameters
    ----------
    url : str | httpx.URL
        The base URL of the CTFd instance
    auth : BaseAuthStrategy | str | None
        The authentication strategy to use. If a string is provided, it is assumed to be a token.
        If `None` is provided, no authentication is used.
    user_agent : str, optional
        The user agent to use for requests, by default "CTFdPy/0.1.0"
    follow_redirects : bool, optional
        Whether to follow redirects, by default False

    Attributes
    ----------
    url : httpx.URL
        The base URL of the CTFd instance
    auth : BaseAuthStrategy
        The authentication strategy to use
    challenges : ChallengesAPI
        Interface for interacting with the `/api/v1/challenges` CTFd API endpoint.
    files : FilesAPI
        Interface for interacting with the `/api/v1/files` CTFd API endpoint.
    flags : FlagsAPI
        Interface for interacting with the `/api/v1/flags` CTFd API endpoint.
    hints : HintsAPI
        Interface for interacting with the `/api/v1/hints` CTFd API endpoint.
    tags : TagsAPI
        Interface for interacting with the `/api/v1/tags` CTFd API endpoint.
    topics : TopicsAPI
        Interface for interacting with the `/api/v1/topics` CTFd API endpoint.
    users : UsersAPI
        Interface for interacting with the `/api/v1/users` CTFd API endpoint.
    """

    @overload
    def __init__(
        self: APIClient[UnauthAuthStrategy],
        url: str | httpx.URL,
        auth: None = None,
        *,
        user_agent: str = "CTFdPy/0.1.0",
        follow_redirects: bool = False,
    ): ...

    @overload
    def __init__(
        self: APIClient[TokenAuthStrategy],
        url: str | httpx.URL,
        auth: str,
        *,
        user_agent: str = "CTFdPy/0.1.0",
        follow_redirects: bool = False,
    ): ...

    @overload
    def __init__(
        self: APIClient[AS],
        url: str | httpx.URL,
        auth: AS,
        *,
        user_agent: str = "CTFdPy/0.1.0",
        follow_redirects: bool = False,
    ): ...

    def __init__(
        self,
        url: str | httpx.URL,
        auth: A | str | None = None,
        *,
        user_agent: str = "CTFdPy/0.1.0",
        follow_redirects: bool = False,
    ):
        if isinstance(auth, str):
            auth = TokenAuthStrategy(auth)
        elif auth is None:
            auth = UnauthAuthStrategy()

        self.auth: A = auth

        self.url = httpx.URL(url)
        self._user_agent = user_agent
        self._follow_redirects = follow_redirects

        self.__sync_client: ContextVar[httpx.Client | None] = ContextVar(
            "sync_client", default=None
        )
        self.__async_client: ContextVar[httpx.AsyncClient | None] = ContextVar(
            "async_client", default=None
        )

        super().__init__(self)

    def _get_client_defaults(self) -> dict[str, str]:
        auth_flow = None
        if self.auth is not None:
            auth_flow = self.auth.get_auth_flow(self)

        headers = {"User-Agent": self._user_agent, "Content-Type": "application/json"}

        return {
            "auth": auth_flow,
            "base_url": self.url,
            "headers": headers,
            "follow_redirects": self._follow_redirects,
        }

    def _create_sync_client(self) -> httpx.Client:
        return httpx.Client(**self._get_client_defaults())

    def get_sync_client(self) -> httpx.Client:
        client = self.__sync_client.get()
        if client is not None:
            return client
        else:
            client = self._create_sync_client()
            self.__sync_client.set(client)
            return client

    def close(self) -> None:
        client = self.__sync_client.get()
        if client is not None:
            client.close()
            self.__sync_client.set(None)

    def __enter__(self) -> APIClient:
        if self.__sync_client.get() is not None:
            raise RuntimeError("Sync HTTP client already exists")
        self.__sync_client.set(self._create_sync_client())
        return self

    def __exit__(
        self,
        exc_type: Type[BaseException] | None = None,
        exc_value: BaseException | None = None,
        traceback: TracebackType | None = None,
    ) -> None:
        cast(httpx.Client, self.__sync_client.get()).close()
        self.__sync_client.set(None)

    def _create_async_client(self) -> httpx.AsyncClient:
        return httpx.AsyncClient(**self._get_client_defaults())

    def get_async_client(self) -> httpx.AsyncClient:
        client = self.__async_client.get()
        if client is not None:
            return client
        else:
            client = self._create_async_client()
            self.__async_client.set(client)
            return client

    async def aclose(self) -> None:
        client = self.__async_client.get()
        if client is not None:
            await client.aclose()
            self.__async_client.set(None)

    async def __aenter__(self) -> APIClient:
        if self.__async_client.get() is not None:
            raise RuntimeError("Async HTTP client already exists")
        self.__async_client.set(self._create_async_client())
        return self

    async def __aexit__(
        self,
        exc_type: Type[BaseException] | None = None,
        exc_value: BaseException | None = None,
        traceback: TracebackType | None = None,
    ) -> None:
        await cast(httpx.AsyncClient, self.__async_client.get()).aclose()
        self.__async_client.set(None)

    def _request(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
    ) -> httpx.Response:
        client = self.get_sync_client()
        try:
            return client.request(
                method,
                url,
                params=params,
                content=content,
                data=data,
                files=files,
                json=json,
                headers=headers,
                cookies=cookies,
            )
        except httpx.TimeoutException as e:
            raise RequestTimeout(request=e.request) from e
        except Exception as e:
            raise CTFdpyException(repr(e)) from e

    async def _arequest(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
    ) -> httpx.Response:
        client = self.get_async_client()
        try:
            return await client.request(
                method,
                url,
                params=params,
                content=content,
                data=data,
                files=files,
                json=json,
                headers=headers,
                cookies=cookies,
            )
        except httpx.TimeoutException as e:
            raise RequestTimeout(request=e.request) from e
        except Exception as e:
            raise CTFdpyException(repr(e)) from e

    @overload
    def _handle_response(
        self,
        response: httpx.Response,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> bool | APIResponse: ...

    @overload
    def _handle_response(
        self,
        response: httpx.Response,
        response_model: Type[T] | TypeAdapter[T] | Callable[[APIResponse], T],
        error_models: dict[str, APIResponseException] | None = None,
    ) -> T: ...

    def _handle_response(
        self,
        response: httpx.Response,
        response_model: (
            Type[T] | TypeAdapter[T] | Callable[[APIResponse], T] | None
        ) = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> T | bool | APIResponse:
        if not response.is_success:
            error_models = error_models or {}
            status_code = response.status_code

            # This is uh... not great
            error_model = error_models.get(
                status_code,
                error_models.get(
                    f"{str(status_code)[0]}XX",
                    error_models.get("default", APIResponseException),
                ),
            )

            raise error_model(response=response)

        response_data: APIResponse = response.json()

        if response_model is None:
            try:
                return response_data["success"]
            except KeyError:
                return response_data
        elif response_data.get("data") is None:
            raise ValueError("Response data expected to have 'data' key")

        if issubclass(response_model, BaseModel):
            response_data = response_model.model_validate(response_data["data"])
        elif isinstance(response_model, TypeAdapter):
            response_data = response_model.validate_python(response_data["data"])
        elif callable(response_model):
            response_data = response_model(response_data)
        else:
            # This should never happen
            raise ValueError("Invalid response model")

        return response_data

    @overload
    def request(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> bool | APIResponse: ...

    @overload
    def request(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        response_model: Type[T] | TypeAdapter[T] | Callable[[APIResponse], T],
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> T: ...

    def request(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
        response_model: (
            Type[T] | TypeAdapter[T] | Callable[[APIResponse], T] | None
        ) = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> T | bool | APIResponse:
        response = self._request(
            method,
            url,
            params=params,
            content=content,
            data=data,
            files=files,
            json=json,
            headers=headers,
            cookies=cookies,
        )
        return self._handle_response(
            response, response_model=response_model, error_models=error_models
        )

    @overload
    async def arequest(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> bool | APIResponse: ...

    @overload
    async def arequest(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        response_model: Type[T] | TypeAdapter[T] | Callable[[APIResponse], T],
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> T: ...

    async def arequest(
        self,
        method: str,
        url: str | httpx.URL,
        *,
        params: QueryParamTypes | None = None,
        content: RequestContent | None = None,
        data: RequestData | None = None,
        files: RequestFiles | None = None,
        json: Any | None = None,
        headers: HeaderTypes | None = None,
        cookies: CookieTypes | None = None,
        response_model: (
            Type[T] | TypeAdapter[T] | Callable[[APIResponse], T] | None
        ) = None,
        error_models: dict[str, APIResponseException] | None = None,
    ) -> T | bool | APIResponse:
        response = await self._arequest(
            method,
            url,
            params=params,
            content=content,
            data=data,
            files=files,
            json=json,
            headers=headers,
            cookies=cookies,
        )
        return self._handle_response(
            response, response_model=response_model, error_models=error_models
        )

    @overload
    def from_env(
        cls: Type[APIClient[AS]],
        *,
        user_agent: str = "CTFdPy/0.1.0",
        follow_redirects: bool = False,
    ) -> APIClient[AS]: ...

    @classmethod
    def from_env(cls: Type[APIClient[AS]], **kwargs) -> APIClient[AS]:
        """
        Create an APIClient from environment variables

        The following environment variables are used:

        - `CTFD_URL`: The base URL of the CTFd instance
        - `CTFD_TOKEN`: The token to use for authentication
        - `CTFD_USERNAME`: The username to use for authentication
        - `CTFD_PASSWORD`: The password to use for authentication
        """
        url = os.getenv("CTFD_URL")
        if url is None:
            raise ValueError("CTFD_URL environment variable must be set")

        auth = None

        token = os.getenv("CTFD_TOKEN")
        if token is not None:
            auth = TokenAuthStrategy(token)

        username = os.getenv("CTFD_USERNAME")
        password = os.getenv("CTFD_PASSWORD")
        if username is not None and password is not None and auth is None:
            auth = CredentialAuthStrategy(username, password)

        return cls(url, auth, **kwargs)

from_env classmethod

from_env(**kwargs) -> APIClient[AS]

Create an APIClient from environment variables

The following environment variables are used:

  • CTFD_URL: The base URL of the CTFd instance
  • CTFD_TOKEN: The token to use for authentication
  • CTFD_USERNAME: The username to use for authentication
  • CTFD_PASSWORD: The password to use for authentication
Source code in ctfdpy\client.py
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
@classmethod
def from_env(cls: Type[APIClient[AS]], **kwargs) -> APIClient[AS]:
    """
    Create an APIClient from environment variables

    The following environment variables are used:

    - `CTFD_URL`: The base URL of the CTFd instance
    - `CTFD_TOKEN`: The token to use for authentication
    - `CTFD_USERNAME`: The username to use for authentication
    - `CTFD_PASSWORD`: The password to use for authentication
    """
    url = os.getenv("CTFD_URL")
    if url is None:
        raise ValueError("CTFD_URL environment variable must be set")

    auth = None

    token = os.getenv("CTFD_TOKEN")
    if token is not None:
        auth = TokenAuthStrategy(token)

    username = os.getenv("CTFD_USERNAME")
    password = os.getenv("CTFD_PASSWORD")
    if username is not None and password is not None and auth is None:
        auth = CredentialAuthStrategy(username, password)

    return cls(url, auth, **kwargs)