diff --git a/pyzipline/zipline.py b/pyzipline/zipline.py index 47afd32..80eafa0 100644 --- a/pyzipline/zipline.py +++ b/pyzipline/zipline.py @@ -331,6 +331,48 @@ class ZiplineApi: raise Forbidden(result.message) raise PyZiplineError(f"{result.status_code}: {result.message}\n{result.data}") + def shorten(self, url: str, vanity: str = None, max_views: int = None, zero_width: bool = False) -> str: + """Shorten a URL + + /// admonition | Requires Authentication + type: warning + /// + + Args: + url (str): URL to shorten + vanity (str): Vanity string to use + max_views (int): Maximum number of views before the URL expires + zero_width (bool): Whether or not to use zero width characters in the shortened URL + + Raises: + Forbidden: The user is not authenticated + PyZiplineError: Raised if the API changes, causing a breaking change in this method + ValueError: Raised if the vanity string already exists, if the vanity string is empty, or if the max views is invalid (less than 0) + + Returns: + str: The shortened URL + """ + headers = {} + if max_views is not None: + headers['Max-Views'] = max_views + if zero_width: + headers['Zws'] = True + + json = {'url': url} if not vanity else {'url': url, 'vanity': vanity} + + result = self._rest_adapter.post(endpoint="shorten", json=json, headers=headers) + + if result.status_code == 200: + return result.data['url'] + + if result.status_code == 400: + raise ValueError(result.message) + + if result.status_code == 401: + raise Forbidden(result.message) + + raise PyZiplineError(f"{result.status_code}: {result.message}\n{result.data}") + def get_user(self, user_id: int) -> User: """Get a user by ID