Skip to content

Story

A representation of a Story on Wattpad. Note: Stories are singletons, unique as per their ID. Two story classes with the same ID are the same.

Attributes:

Name Type Description
id str

Lowercased ID of this Story.

user User

The User who authored this Story.

recommended list[Story]

Stories recommended from this Story.

data StoryModel

Story Data from the Wattpad API.

Source code in src/wattpad/wattpad.py
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
class Story(metaclass=create_singleton()):
    """A representation of a Story on Wattpad.
    **Note**: Stories are singletons, unique as per their ID. Two story classes with the same ID are the _same_.

    Attributes:
        id (str): Lowercased ID of this Story.
        user (User): The User who authored this Story.
        recommended (list[Story]): Stories recommended from this Story.
        data (StoryModel): Story Data from the Wattpad API.
    """

    def __init__(self, id: str, user: Optional[User] = None, **kwargs):
        """Create a Story object.

        Args:
            id (str): The ID of the Story.
            user (User): The User who authored this Story.
        """
        self.id = id.lower()
        self.user: Optional[User] = user
        self.recommended: list[Story] = []
        # self.parts: list[Part]  # ! NotImplemented. In the future, if Part text retrieval is a part of this library, that would warrant the creation of a seperate Part singleton. Right now, having self.parts would cause inconsistency with the rest of the library.
        self.data = StoryModel(id=self.id, **kwargs)

    def __repr__(self) -> str:
        return f"<Story id={self.id}>"

    async def fetch(self, include: bool | StoryModelFieldsType = False) -> dict:
        """Populates a Story's data. Call this method after instantiation.

        Args:
            include (bool | StoryModelFieldsType, optional): Fields to fetch. True fetches all fields. Defaults to False.

        Returns:
            dict: The raw API Response.
        """
        if include is False:
            include_fields: StoryModelFieldsType = {}
        elif include is True:
            include_fields: StoryModelFieldsType = {
                key: True for key in get_fields(StoryModel)  # type: ignore
            }
        else:
            include_fields: StoryModelFieldsType = include

        if "user" in include_fields:
            if include_fields["user"] is True:
                include_fields["user"] = cast(
                    UserModelFieldsType, {key: True for key in get_fields(UserModel)}  # type: ignore
                )
            elif include_fields["user"] is False:
                include_fields["user"] = {"username": True}
            else:
                include_fields["user"]["username"] = True
        else:
            include_fields["user"] = {"username": True}

        data = cast(
            dict,
            await fetch_url(
                build_url(f"stories/{self.data.id}", fields=dict(include_fields))
            ),
        )
        if "id" in data:
            data.pop("id")
        if "user" in data:
            user_data = data.pop("user")
            user = User(user_data.pop("username"))
            user._update_data(**user_data)
            self.user = user

        self.data = StoryModel(id=self.id, **data)

        return data

    async def fetch_recommended(
        self,
        include: bool | StoryModelFieldsType = False,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
    ) -> list:
        """Fetch Stories recommended from this Story.

        Args:
            include (bool | StoryModelFieldsType, optional): Fields to fetch of the recommended stories. True fetches all fields. Defaults to False.
            limit (Optional[int], optional): Maximum number of users to return at once. Use this alongside `offset` for better performance. Defaults to None.
            offset (Optional[int], optional): Number of users to skip before returning followers. Use this alongside `limit` for better performance. Defaults to None.

        Returns:
            dict: The raw API Response.
        """
        if include is False:
            include_fields: StoryModelFieldsType = {}
        elif include is True:
            include_fields: StoryModelFieldsType = {
                key: True for key in get_fields(StoryModel)  # type: ignore
            }
        else:
            include_fields: StoryModelFieldsType = include

        include_fields["id"] = True

        if "user" in include_fields:
            if include_fields["user"] is True:
                include_fields["user"] = cast(
                    UserModelFieldsType, {key: True for key in get_fields(UserModel)}  # type: ignore
                )
            elif include_fields["user"] is False:
                include_fields["user"] = {"username": True}
            else:
                include_fields["user"]["username"] = True
        else:
            include_fields["user"] = {"username": True}

        data = cast(
            list[dict],
            await fetch_url(
                build_url(
                    f"stories/{self.data.id}/recommended",
                    fields=dict(include_fields),
                    limit=limit,
                    offset=offset,
                )
            ),
        )

        self.recommended = [Story(**story) for story in data]

        return data

    def _update_data(self, **kwargs):
        """Updates self.data with kwargs, overwriting any duplicate values with a preference towards kwargs.

        Returns:
            None: Nothing is returned.
        """
        self.data = self.data.model_copy(
            update=convert_from_aliases(kwargs, self.data), deep=True
        )

__init__(id, user=None, **kwargs) #

Create a Story object.

Parameters:

Name Type Description Default
id str

The ID of the Story.

required
user User

The User who authored this Story.

None
Source code in src/wattpad/wattpad.py
354
355
356
357
358
359
360
361
362
363
364
365
def __init__(self, id: str, user: Optional[User] = None, **kwargs):
    """Create a Story object.

    Args:
        id (str): The ID of the Story.
        user (User): The User who authored this Story.
    """
    self.id = id.lower()
    self.user: Optional[User] = user
    self.recommended: list[Story] = []
    # self.parts: list[Part]  # ! NotImplemented. In the future, if Part text retrieval is a part of this library, that would warrant the creation of a seperate Part singleton. Right now, having self.parts would cause inconsistency with the rest of the library.
    self.data = StoryModel(id=self.id, **kwargs)

fetch(include=False) async #

Populates a Story's data. Call this method after instantiation.

Parameters:

Name Type Description Default
include bool | StoryModelFieldsType

Fields to fetch. True fetches all fields. Defaults to False.

False

Returns:

Name Type Description
dict dict

The raw API Response.

Source code in src/wattpad/wattpad.py
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
async def fetch(self, include: bool | StoryModelFieldsType = False) -> dict:
    """Populates a Story's data. Call this method after instantiation.

    Args:
        include (bool | StoryModelFieldsType, optional): Fields to fetch. True fetches all fields. Defaults to False.

    Returns:
        dict: The raw API Response.
    """
    if include is False:
        include_fields: StoryModelFieldsType = {}
    elif include is True:
        include_fields: StoryModelFieldsType = {
            key: True for key in get_fields(StoryModel)  # type: ignore
        }
    else:
        include_fields: StoryModelFieldsType = include

    if "user" in include_fields:
        if include_fields["user"] is True:
            include_fields["user"] = cast(
                UserModelFieldsType, {key: True for key in get_fields(UserModel)}  # type: ignore
            )
        elif include_fields["user"] is False:
            include_fields["user"] = {"username": True}
        else:
            include_fields["user"]["username"] = True
    else:
        include_fields["user"] = {"username": True}

    data = cast(
        dict,
        await fetch_url(
            build_url(f"stories/{self.data.id}", fields=dict(include_fields))
        ),
    )
    if "id" in data:
        data.pop("id")
    if "user" in data:
        user_data = data.pop("user")
        user = User(user_data.pop("username"))
        user._update_data(**user_data)
        self.user = user

    self.data = StoryModel(id=self.id, **data)

    return data

Fetch Stories recommended from this Story.

Parameters:

Name Type Description Default
include bool | StoryModelFieldsType

Fields to fetch of the recommended stories. True fetches all fields. Defaults to False.

False
limit Optional[int]

Maximum number of users to return at once. Use this alongside offset for better performance. Defaults to None.

None
offset Optional[int]

Number of users to skip before returning followers. Use this alongside limit for better performance. Defaults to None.

None

Returns:

Name Type Description
dict list

The raw API Response.

Source code in src/wattpad/wattpad.py
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
async def fetch_recommended(
    self,
    include: bool | StoryModelFieldsType = False,
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> list:
    """Fetch Stories recommended from this Story.

    Args:
        include (bool | StoryModelFieldsType, optional): Fields to fetch of the recommended stories. True fetches all fields. Defaults to False.
        limit (Optional[int], optional): Maximum number of users to return at once. Use this alongside `offset` for better performance. Defaults to None.
        offset (Optional[int], optional): Number of users to skip before returning followers. Use this alongside `limit` for better performance. Defaults to None.

    Returns:
        dict: The raw API Response.
    """
    if include is False:
        include_fields: StoryModelFieldsType = {}
    elif include is True:
        include_fields: StoryModelFieldsType = {
            key: True for key in get_fields(StoryModel)  # type: ignore
        }
    else:
        include_fields: StoryModelFieldsType = include

    include_fields["id"] = True

    if "user" in include_fields:
        if include_fields["user"] is True:
            include_fields["user"] = cast(
                UserModelFieldsType, {key: True for key in get_fields(UserModel)}  # type: ignore
            )
        elif include_fields["user"] is False:
            include_fields["user"] = {"username": True}
        else:
            include_fields["user"]["username"] = True
    else:
        include_fields["user"] = {"username": True}

    data = cast(
        list[dict],
        await fetch_url(
            build_url(
                f"stories/{self.data.id}/recommended",
                fields=dict(include_fields),
                limit=limit,
                offset=offset,
            )
        ),
    )

    self.recommended = [Story(**story) for story in data]

    return data