200 lines
11 KiB
Python
200 lines
11 KiB
Python
# coding: utf-8
|
|
|
|
"""
|
|
PeerTube
|
|
|
|
The PeerTube API is built on HTTP(S) and is RESTful. You can use your favorite HTTP/REST library for your programming language to use PeerTube. The spec API is fully compatible with [openapi-generator](https://github.com/OpenAPITools/openapi-generator/wiki/API-client-generator-HOWTO) which generates a client SDK in the language of your choice - we generate some client SDKs automatically: - [Python](https://framagit.org/framasoft/peertube/clients/python) - [Go](https://framagit.org/framasoft/peertube/clients/go) - [Kotlin](https://framagit.org/framasoft/peertube/clients/kotlin) See the [REST API quick start](https://docs.joinpeertube.org/api/rest-getting-started) for a few examples of using the PeerTube API. # Authentication When you sign up for an account on a PeerTube instance, you are given the possibility to generate sessions on it, and authenticate there using an access token. Only __one access token can currently be used at a time__. ## Roles Accounts are given permissions based on their role. There are three roles on PeerTube: Administrator, Moderator, and User. See the [roles guide](https://docs.joinpeertube.org/admin/managing-users#roles) for a detail of their permissions. # Errors The API uses standard HTTP status codes to indicate the success or failure of the API call, completed by a [RFC7807-compliant](https://tools.ietf.org/html/rfc7807) response body. ``` HTTP 1.1 404 Not Found Content-Type: application/problem+json; charset=utf-8 { \"detail\": \"Video not found\", \"docs\": \"https://docs.joinpeertube.org/api-rest-reference.html#operation/getVideo\", \"status\": 404, \"title\": \"Not Found\", \"type\": \"about:blank\" } ``` We provide error `type` values for [a growing number of cases](https://github.com/Chocobozzz/PeerTube/blob/develop/packages/models/src/server/core-error-code.enum.ts), but it is still optional. Types are used to disambiguate errors that bear the same status code and are non-obvious: ``` HTTP 1.1 403 Forbidden Content-Type: application/problem+json; charset=utf-8 { \"detail\": \"Cannot get this video regarding follow constraints\", \"docs\": \"https://docs.joinpeertube.org/api-rest-reference.html#operation/getVideo\", \"status\": 403, \"title\": \"Forbidden\", \"type\": \"https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/does_not_respect_follow_constraints\" } ``` Here a 403 error could otherwise mean that the video is private or blocklisted. ### Validation errors Each parameter is evaluated on its own against a set of rules before the route validator proceeds with potential testing involving parameter combinations. Errors coming from validation errors appear earlier and benefit from a more detailed error description: ``` HTTP 1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { \"detail\": \"Incorrect request parameters: id\", \"docs\": \"https://docs.joinpeertube.org/api-rest-reference.html#operation/getVideo\", \"instance\": \"/api/v1/videos/9c9de5e8-0a1e-484a-b099-e80766180\", \"invalid-params\": { \"id\": { \"location\": \"params\", \"msg\": \"Invalid value\", \"param\": \"id\", \"value\": \"9c9de5e8-0a1e-484a-b099-e80766180\" } }, \"status\": 400, \"title\": \"Bad Request\", \"type\": \"about:blank\" } ``` Where `id` is the name of the field concerned by the error, within the route definition. `invalid-params.<field>.location` can be either 'params', 'body', 'header', 'query' or 'cookies', and `invalid-params.<field>.value` reports the value that didn't pass validation whose `invalid-params.<field>.msg` is about. ### Deprecated error fields Some fields could be included with previous versions. They are still included but their use is deprecated: - `error`: superseded by `detail` - `code`: superseded by `type` (which is now an URI) # Rate limits We are rate-limiting all endpoints of PeerTube's API. Custom values can be set by administrators: | Endpoint (prefix: `/api/v1`) | Calls | Time frame | |------------------------------|---------------|--------------| | `/*` | 50 | 10 seconds | | `POST /users/token` | 15 | 5 minutes | | `POST /users/register` | 2<sup>*</sup> | 5 minutes | | `POST /users/ask-send-verify-email` | 3 | 5 minutes | Depending on the endpoint, <sup>*</sup>failed requests are not taken into account. A service limit is announced by a `429 Too Many Requests` status code. You can get details about the current state of your rate limit by reading the following headers: | Header | Description | |-------------------------|------------------------------------------------------------| | `X-RateLimit-Limit` | Number of max requests allowed in the current time period | | `X-RateLimit-Remaining` | Number of remaining requests in the current time period | | `X-RateLimit-Reset` | Timestamp of end of current time period as UNIX timestamp | | `Retry-After` | Seconds to delay after the first `429` is received | # CORS This API features [Cross-Origin Resource Sharing (CORS)](https://fetch.spec.whatwg.org/), allowing cross-domain communication from the browser for some routes: | Endpoint | |------------------------- ---| | `/api/*` | | `/download/*` | | `/lazy-static/*` | | `/.well-known/webfinger` | In addition, all routes serving ActivityPub are CORS-enabled for all origins.
|
|
|
|
The version of the OpenAPI document: 5.2.0
|
|
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
|
|
|
Do not edit the class manually.
|
|
""" # noqa: E501
|
|
|
|
from typing import Any, Optional
|
|
from typing_extensions import Self
|
|
|
|
class OpenApiException(Exception):
|
|
"""The base exception class for all OpenAPIExceptions"""
|
|
|
|
|
|
class ApiTypeError(OpenApiException, TypeError):
|
|
def __init__(self, msg, path_to_item=None, valid_classes=None,
|
|
key_type=None) -> None:
|
|
""" Raises an exception for TypeErrors
|
|
|
|
Args:
|
|
msg (str): the exception message
|
|
|
|
Keyword Args:
|
|
path_to_item (list): a list of keys an indices to get to the
|
|
current_item
|
|
None if unset
|
|
valid_classes (tuple): the primitive classes that current item
|
|
should be an instance of
|
|
None if unset
|
|
key_type (bool): False if our value is a value in a dict
|
|
True if it is a key in a dict
|
|
False if our item is an item in a list
|
|
None if unset
|
|
"""
|
|
self.path_to_item = path_to_item
|
|
self.valid_classes = valid_classes
|
|
self.key_type = key_type
|
|
full_msg = msg
|
|
if path_to_item:
|
|
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
|
|
super(ApiTypeError, self).__init__(full_msg)
|
|
|
|
|
|
class ApiValueError(OpenApiException, ValueError):
|
|
def __init__(self, msg, path_to_item=None) -> None:
|
|
"""
|
|
Args:
|
|
msg (str): the exception message
|
|
|
|
Keyword Args:
|
|
path_to_item (list) the path to the exception in the
|
|
received_data dict. None if unset
|
|
"""
|
|
|
|
self.path_to_item = path_to_item
|
|
full_msg = msg
|
|
if path_to_item:
|
|
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
|
|
super(ApiValueError, self).__init__(full_msg)
|
|
|
|
|
|
class ApiAttributeError(OpenApiException, AttributeError):
|
|
def __init__(self, msg, path_to_item=None) -> None:
|
|
"""
|
|
Raised when an attribute reference or assignment fails.
|
|
|
|
Args:
|
|
msg (str): the exception message
|
|
|
|
Keyword Args:
|
|
path_to_item (None/list) the path to the exception in the
|
|
received_data dict
|
|
"""
|
|
self.path_to_item = path_to_item
|
|
full_msg = msg
|
|
if path_to_item:
|
|
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
|
|
super(ApiAttributeError, self).__init__(full_msg)
|
|
|
|
|
|
class ApiKeyError(OpenApiException, KeyError):
|
|
def __init__(self, msg, path_to_item=None) -> None:
|
|
"""
|
|
Args:
|
|
msg (str): the exception message
|
|
|
|
Keyword Args:
|
|
path_to_item (None/list) the path to the exception in the
|
|
received_data dict
|
|
"""
|
|
self.path_to_item = path_to_item
|
|
full_msg = msg
|
|
if path_to_item:
|
|
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
|
|
super(ApiKeyError, self).__init__(full_msg)
|
|
|
|
|
|
class ApiException(OpenApiException):
|
|
|
|
def __init__(
|
|
self,
|
|
status=None,
|
|
reason=None,
|
|
http_resp=None,
|
|
*,
|
|
body: Optional[str] = None,
|
|
data: Optional[Any] = None,
|
|
) -> None:
|
|
self.status = status
|
|
self.reason = reason
|
|
self.body = body
|
|
self.data = data
|
|
self.headers = None
|
|
|
|
if http_resp:
|
|
if self.status is None:
|
|
self.status = http_resp.status
|
|
if self.reason is None:
|
|
self.reason = http_resp.reason
|
|
if self.body is None:
|
|
try:
|
|
self.body = http_resp.data.decode('utf-8')
|
|
except Exception:
|
|
pass
|
|
self.headers = http_resp.getheaders()
|
|
|
|
@classmethod
|
|
def from_response(
|
|
cls,
|
|
*,
|
|
http_resp,
|
|
body: Optional[str],
|
|
data: Optional[Any],
|
|
) -> Self:
|
|
if http_resp.status == 400:
|
|
raise BadRequestException(http_resp=http_resp, body=body, data=data)
|
|
|
|
if http_resp.status == 401:
|
|
raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
|
|
|
|
if http_resp.status == 403:
|
|
raise ForbiddenException(http_resp=http_resp, body=body, data=data)
|
|
|
|
if http_resp.status == 404:
|
|
raise NotFoundException(http_resp=http_resp, body=body, data=data)
|
|
|
|
if 500 <= http_resp.status <= 599:
|
|
raise ServiceException(http_resp=http_resp, body=body, data=data)
|
|
raise ApiException(http_resp=http_resp, body=body, data=data)
|
|
|
|
def __str__(self):
|
|
"""Custom error messages for exception"""
|
|
error_message = "({0})\n"\
|
|
"Reason: {1}\n".format(self.status, self.reason)
|
|
if self.headers:
|
|
error_message += "HTTP response headers: {0}\n".format(
|
|
self.headers)
|
|
|
|
if self.data or self.body:
|
|
error_message += "HTTP response body: {0}\n".format(self.data or self.body)
|
|
|
|
return error_message
|
|
|
|
|
|
class BadRequestException(ApiException):
|
|
pass
|
|
|
|
|
|
class NotFoundException(ApiException):
|
|
pass
|
|
|
|
|
|
class UnauthorizedException(ApiException):
|
|
pass
|
|
|
|
|
|
class ForbiddenException(ApiException):
|
|
pass
|
|
|
|
|
|
class ServiceException(ApiException):
|
|
pass
|
|
|
|
|
|
def render_path(path_to_item):
|
|
"""Returns a string representation of a path"""
|
|
result = ""
|
|
for pth in path_to_item:
|
|
if isinstance(pth, int):
|
|
result += "[{0}]".format(pth)
|
|
else:
|
|
result += "['{0}']".format(pth)
|
|
return result
|