Quickstart¶
Let's hit the ground running by briefly describing all the functions in the library.
from wattpad import User
help(User)
Help on class User in module wattpad.wattpad: class User(builtins.object) | User(*args, **kwargs) | | A representation of a User on Wattpad. | **Note**: Users are singletons, unique as per their username. Two user classes with the same username are the _same_. | | Attributes: | username (str): Lowercased username of this User. | stories (list[Story]): Stories authored by this User. | followers (list[User]): Users that follow this User. | following (list[User]): Users this User follows. | lists (set[List]): Lists created by this User. | data (UserModel): User Data from the Wattpad API. | | Methods defined here: | | __init__(self, username: 'str', **kwargs) | Create a User object. | | Args: | username (str): The username of this User. | **kwargs (any): Arguments to pass directly to the underlying `UserModel`. These are ignored if the User has been instantiated earlier in the runtime. | | __repr__(self) -> 'str' | Return repr(self). | | async fetch(self, include: 'bool | UserModelFieldsType' = False) -> 'dict' | Populates a User's data. Call this method after instantiation. | | Args: | include (bool | UserModelFieldsType, optional): Fields to fetch. True fetches all fields. Defaults to False. | | Returns: | dict: The raw API Response. | | async fetch_followers(self, include: 'bool | UserModelFieldsType' = False, limit: 'Optional[int]' = None, offset: 'Optional[int]' = None) -> 'dict' | Fetches the User's followers. | | Args: | include (bool | UserModelFieldsType, optional): Fields of the following users' to fetch. 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. | | async fetch_following(self, include: 'bool | UserModelFieldsType' = False, limit: 'Optional[int]' = None, offset: 'Optional[int]' = None) -> 'dict' | Fetch the users this User follows. | | Args: | include (bool | UserModelFieldsType, optional): Fields of the followed users' to fetch. 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. | | async fetch_lists(self, include: 'bool | ListModelFieldsType' = False, limit: 'Optional[int]' = None, offset: 'Optional[int]' = None) -> 'dict' | Fetch a User's lists. | | Args: | include (bool | ListModelFieldsType, optional): Fields of the lists to fetch. 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. | | async fetch_stories(self, include: 'bool | StoryModelFieldsType' = False) -> 'dict' | Fetch a User's authored stories. | | Args: | include (bool | StoryModelFieldsType, optional): Fields of authored stories to fetch. True fetches all fields. Defaults to False. | | Returns: | dict: The raw API Response. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)
from rich import print
user = User("WattpadBooks")
Data fetched from the users endpoint of the API is present in the data attribute.
print(user.data)
UserModel( username='wattpadbooks', avatar=None, is_private=None, background_url=None, follower=None, following=None, name=None, description=None, status=None, gender=None, gender_code=None, language=None, locale=None, create_date=None, modify_date=None, location=None, verified=None, ambassador=None, facebook=None, twitter=None, website=None, lulu=None, smashwords=None, bubok=None, votes_received=None, num_stories_published=None, num_following=None, num_followers=None, num_messages=None, num_lists=None, verified_email=None, preferred_categories=None, allow_crawler=None, deeplink=None, is_muted=None, birthdate=None, inbox=None, notifications=None, connected_services=None, age=None, email=None, has_password=None )
The object currently has no data. Let's fetch some from the API.
api_response = await user.fetch({
"description": True,
"numFollowers": True
})
print(api_response)
{ 'description': "Wattpad Books brings stories the world needs to hear, brought to life by your favorite writers, right into your hands. Welcome home. 🏡🧡\n\nStay in the know of all the latest launches from Wattpad Books. Looking for your next literary obsession? Crossing your fingers for more work from your favorite creator? Follow us here to be the first to hear about new releases, author interviews, and more!\n\nWe see your dreams, and we want to help you achieve them. If you're hoping to get published, our advice is to keep doing what you love: writing. Every book published by Wattpad Books was born right here on Wattpad. ⭐️\n\n🔈Follow Wattpad Books:\nTwitter: twitter.com/wattpadbooks\nInstagram: wattpadbooks\nFacebook: facebook.com/wattpad", 'numFollowers': 60871 }
All functions prefixed with fetch
return the JSON-Decoded Response from the API. Though, all the data is copied into the data
attribute.
Available parameters to fetch
functions will show up in autocomplete recommendations. If not, the documentation has information on the same.
Accessing fetched data¶
print(user.data.description)
Wattpad Books brings stories the world needs to hear, brought to life by your favorite writers, right into your hands. Welcome home. 🏡🧡 Stay in the know of all the latest launches from Wattpad Books. Looking for your next literary obsession? Crossing your fingers for more work from your favorite creator? Follow us here to be the first to hear about new releases, author interviews, and more! We see your dreams, and we want to help you achieve them. If you're hoping to get published, our advice is to keep doing what you love: writing. Every book published by Wattpad Books was born right here on Wattpad. ⭐️ 🔈Follow Wattpad Books: Twitter: twitter.com/wattpadbooks Instagram: wattpadbooks Facebook: facebook.com/wattpad
All available attributes for user.data
from wattpad.models import UserModel
from wattpad.utils import get_fields
print(get_fields(UserModel, prefer_alias=False))
[ 'username', 'avatar', 'is_private', 'background_url', 'follower', 'following', 'name', 'description', 'status', 'gender', 'gender_code', 'language', 'locale', 'create_date', 'modify_date', 'location', 'verified', 'ambassador', 'facebook', 'twitter', 'website', 'lulu', 'smashwords', 'bubok', 'votes_received', 'num_stories_published', 'num_following', 'num_followers', 'num_messages', 'num_lists', 'verified_email', 'preferred_categories', 'allow_crawler', 'deeplink', 'is_muted', 'birthdate', 'inbox', 'notifications', 'connected_services', 'age', 'email', 'has_password' ]
Fetching stories¶
await user.fetch_stories({"title": True})
await user.fetch_stories({"createDate": True})
await user.fetch_stories({"description": True, "tagRankings": True})
print(user.stories)
print(user.stories[0].data)
[ <Story id=237369078>, <Story id=224300595>, <Story id=235072518>, <Story id=220579773>, <Story id=205141809>, <Story id=208192934> ]
StoryModel( id='237369078', title='Wattpad Books Presents', create_date='2020-08-18T20:37:20Z', modify_date=None, vote_count=None, read_count=None, comment_count=None, description="Welcome to Wattpad Books! Here you can find all of the titles that we have published or will be publishing. We'll be adding new titles as we acquire them, so stay tuned! You can purchase Wattpad Books through our website books.wattpad.com or from your favourite retailer. You can also read them here on Wattpad.", completed=None, tags=None, rating=None, mature=None, url=None, is_paywalled=None, cover=None, cover_timestamp=None, categories=None, copyright=None, first_part_id=None, num_parts=None, deleted=None, first_published_part=None, last_published_part=None, language=None, user=None, parts=[], tag_rankings=[ {'name': 'feel', 'rank': 31, 'total': 3107}, {'name': 'authors', 'rank': 68, 'total': 3586}, {'name': 'publishing', 'rank': 22, 'total': 1004}, {'name': 'published', 'rank': 61, 'total': 1856}, {'name': 'ya', 'rank': 579, 'total': 11095}, {'name': 'feelgood', 'rank': 172, 'total': 3070}, {'name': 'wattpadbooks', 'rank': 143, 'total': 1940} ] )
Available parameters to fetch
functions will show up in autocomplete recommendations. If not, the documentation has information on the same.
As displayed above, story data can be fetched like so.
Fetched data concatenates and overwrites pre-existing data. Keys are populated or overwritten with data from the responses.
User Fetching¶
Fetching a user's followers
, following
can be achieved like so:
await user.fetch_followers(include={'username': True, "description": True}, limit=1, offset=4)
for follower in user.followers:
print(follower)
print(follower.data.description)
break
<User username=magicalfairykitten>
As fetch_followers
and fetch_following
are computationally expensive on the API-Side, it's recommended to use the limit
and offset
parameters to paginate responses. This prevents long response times and response timeouts.
Here's an example of pagination:
await user.fetch({"numFollowers": True})
total = user.data.num_followers
assert total
limit = 10
chunks = total // limit
if chunks > 199:
chunks = 199 # ! Wattpad fails with an offset over 1990.
# ! Since this is a demo, we'll retrieve two chunks only.
chunks = 2
for chunk in range(chunks):
print(f"Processing Chunk: {chunk}")
await user.fetch_followers({"username": True}, limit=limit, offset=limit*chunk)
await user.fetch_followers({"username": True}, offset=len(user.followers))
print(f"{len(user.followers)} followers have been fetched for {user}.")
Processing Chunk: 0
Processing Chunk: 1
30 followers have been fetched for <User username=wattpadbooks>.
Fetching stories¶
await user.fetch_stories({"title": True})
print(user.stories[0], user.stories[0].data.title)
<Story id=237369078> Wattpad Books Presents
All available attributes for story.data
Stories¶
from wattpad import Story
story = Story("237369078")
await story.fetch({"description": True})
print(story.data.description)
Welcome to Wattpad Books! Here you can find all of the titles that we have published or will be publishing. We'll be adding new titles as we acquire them, so stay tuned! You can purchase Wattpad Books through our website books.wattpad.com or from your favourite retailer. You can also read them here on Wattpad.
Fetching recommended stories¶
Wattpad has a recommendation algorithm which recommends stories based on one provided.
Use limit
and offset
as you did for user.fetch_followers
and user.fetch_following
.
await story.fetch_recommended({"title": True, "voteCount": True}, limit=1, offset=0)
print(story.recommended[0].data.title)
Madame Bovary
Story Data¶
Available data from story.data
.
from wattpad.models import StoryModel
from wattpad.utils import get_fields
print(get_fields(StoryModel, prefer_alias=False))
[ 'id', 'title', 'create_date', 'modify_date', 'vote_count', 'read_count', 'comment_count', 'description', 'completed', 'tags', 'rating', 'mature', 'url', 'is_paywalled', 'cover', 'cover_timestamp', 'categories', 'copyright', 'first_part_id', 'num_parts', 'deleted', 'first_published_part', 'last_published_part', 'language', 'user', 'parts', 'tag_rankings' ]
Lists¶
Lists are collections of stories, made by Users.
Use limit
and offset
similarly to story.fetch_recommended
, user.fetch_following
, and user.fetch_followers
. List responses are especially large and time-taking.
await user.fetch_lists({"name": True, "stories": {"title": True}}, limit=1, offset=2)
for list_ in user.lists:
print(list_.name, list_.id)
for story in list_.stories:
print(story.data.title)
789566085
The Summer I Drowned (Wattpad Books Edition)
The Summer of '98 (Wattpad Books Edition)
Night Owls and Summer Skies (Wattpad Books Edition)
ENTWINED
The Invincible Summer of Juniper Jones (Wattpad Books Edition)
All available attributes for list_.data
.
from wattpad.models import ListModel
from wattpad.utils import get_fields
print(get_fields(ListModel, prefer_alias=False))
['id', 'name', 'stories']
That's all! If you need help, look here.
TheOnlyWayUp © 2024