Skip to content

services

Module for exporting all services.

BaseService

Bases: ABC

The base service from which all the other services inherit.

Parameters:

Name Type Description Default
http_service HttpService

The http service to use for requests.

required
serializer Serializer

The serializer used for deserializing API JSON data.

required
Source code in barch\services\base.py
class BaseService(abc.ABC):
    """The base service from which all the other services inherit.

    Args:
        http_service: The http service to use for requests.
        serializer: The serializer used for deserializing API JSON data.
    """

    __slots__ = ("_http", "_serializer")

    def __init__(
        self, http_service: HttpService, serializer: serializer.Serializer
    ) -> None:
        self._http = http_service
        self._serializer = serializer

CharacterService

Bases: BaseService

The service that handles all the methods related to characters.

Source code in barch\services\character.py
class CharacterService(BaseService):
    """The service that handles all the methods related to characters."""

    __slots__ = ()

    async def _get_all_characters(
        self, is_jp: bool = False
    ) -> ResultT[list[Character]]:
        """Internal method for getting all character details which is used by the
        EN and JP version service methods.

        Keyword Args:
            is_jp: the optional boolean flag, which specifies if the character details need to be fetched
                in EN or JP version.

        Returns:
            [`Result`][barch.Result] containing `list[Character]` on success or error data on error.
        """

        if is_jp:
            route = endpoints.GET_ALL_CHARACTERS_JP.generate_route()
        else:
            route = endpoints.GET_ALL_CHARACTERS.generate_route()

        result = await self._http.fetch(route)

        if isinstance(result, HttpErrorResponse):
            return Error(result)

        return Success(
            [self._serializer.deserialize_character(element) for element in result.data]
        )

    async def get_all_characters(self) -> ResultT[list[Character]]:
        """Get all the characters with details EN version.

        Returns:
            [`Result`][barch.Result] containing `list[Character]` on success or error data on error.

        ??? example

            ```py
            from barch import Client

            client = Client()

            result = await client.character.get_all_characters()

            if result.is_success:
                characters = result.value

            if result.is_error:
                error = result.error

            await client.close()
            ```
        """

        return await self._get_all_characters()

    async def get_all_characters_jp(self) -> ResultT[list[Character]]:
        """Get all the characters with details japanese version.

        Returns:
            [`Result`][barch.Result] containing `list[Character]` on success or error data on error.

        ??? example

            ```py
            from barch import Client

            client = Client()

            result = await client.character.get_all_characters_jp()

            if result.is_success:
                characters = result.value

            if result.is_error:
                error = result.error

            await client.close()
        """

        return await self._get_all_characters(is_jp=True)

    async def _get_character(
        self, name: str | None = None, id: int | None = None, is_jp: bool = False
    ) -> ResultT[CharacterDetails]:
        """Internal method used to get a single character details, which is used by both EN and JP versions.

        Keyword Args:
            name: The optional name of the chracter either for EN and JP version.

            id: The optional id of the character.

            is_jp: The optional is_jp flag which specifies if the character details need to be fetched in EN or JP version.

        Returns:
            [`Result`][barch.Result] containing `CharacterDetails` on success or error data on error.

        """

        params: dict = {}

        if id:
            params.update({"id": "true"})

        if is_jp:
            route = endpoints.GET_CHARACTER_JP.generate_route(
                name if name else id
            ).with_params(params if params else None)

        else:
            route = endpoints.GET_CHARACTER.generate_route(
                name if name else id
            ).with_params(params if params else None)

        result = await self._http.fetch(route)

        if isinstance(result, HttpErrorResponse):
            return Error(result)

        return Success(self._serializer.deserialize_character_details(result.data))

    async def get_character(
        self, name: str | None = None, id: int | None = None
    ) -> ResultT[CharacterDetails]:
        """Get a single character either by name or id, EN version.
        Atleast one parameter, either name or id need to be specified.

        Keyword Args:
            name: The optional name of the character.
            id: The optional id of the character.

        Returns:
            [`Result`][barch.Result] containing `CharacterDetails]` on success or error data on error.

        Raises:
            ValueError: When no arguments are given

        ??? example

            ```py
            from barch import Client

            client = Client()

            result = await client.character.get_character(id=10000)

            if result.is_success:
                characters = result.value

            if result.is_error:
                error = result.error

            await client.close()
            ```
        """

        if name or id:
            return await self._get_character(name=name, id=id)

        else:
            raise ValueError("Atleast one parameter must be specified.")

    async def get_character_jp(
        self, name: str | None = None, id: int | None = None
    ) -> ResultT[CharacterDetails]:
        """Get a single character either by name or id, JP version.
        Atleast one parameter, either name or id need to be specified.

        Keyword Args:
            name: The optional name of the character. Note that the character input name needs to be JP.
            id: The optional id of the character.

        Returns:
            [`Result`][barch.Result] containing `CharacterDetails` on success or error data on error.

        ??? example

            ```py
            from barch import Client

            client = Client()

            result = await client.character.get_character_jp(id=10000)

            if result.is_success:
                characters = result.value

            if result.is_error:
                error = result.error

            await client.close()
            ```"""

        return await self._get_character(name=name, id=id, is_jp=True)

    async def get_character_by_query(
        self,
        role: Role | None = None,
        type: str | None = None,
        school: str | None = None,
        club: str | None = None,
        position: Position | None = None,
        weapon: str | None = None,
        damage: str | None = None,
        armor: str | None = None,
    ) -> ResultT[Characters]:
        """Get a single character details based on different parameters.
        Atleast one parameter must be specified. Multiple parameters can be specified
        to get characters based on different filters.

        Keyword Args:
            role: The optional `Role` enum parameter, which gets characters by role.
            type: The optional `type` parameter, which gets characters by the type.
            school: The optional `school` parameter, which gets characters by their school.
            club: The optional `club` parameter, which gets characters by their club.
            position: The optional `Position` enum parameter, which gets characters by their position.
            weapon: The optional `weapon` parameter, which gets characters by their weapon.
            damage: The optional `damage` parameter.
            armor: The optional `armor` parameter.

        Returns:
            [`Result`][barch.Result] containing `Characters` on success or error data on error.

        Raises:
            ValueError: When no arguments are given.

        ??? example

            ```py
            from barch import Client, Role, Position

            client = Client()

            result = await client.character.get_character_by_query(role=Role.Dealer, position=Position.Back)

            if result.is_success:
                characters = result.value

            if result.is_error:
                error = result.error

            await client.close()
        """

        if any([role, type, school, club, position, weapon, damage, armor]):
            params = {
                "role": role.value if role else "",
                "type": type if type else "",
                "school": school if school else "",
                "club": club if club else "",
                "position": position.value if position else "",
                "weapon": weapon if weapon else "",
                "damage": damage if damage else "",
                "armor": armor if armor else "",
            }

            route = endpoints.GET_CHARACTER_QUERY.generate_route().with_params(params)
            result = await self._http.fetch(route)

            if isinstance(result, HttpErrorResponse):
                return Error(result)

            return Success(
                [
                    self._serializer.deserialize_characters_from_query(char)
                    for char in result.data
                ]
            )

        else:
            raise ValueError("Atleast one parameter must be specified.")

get_all_characters async

get_all_characters() -> ResultT[list[Character]]

Get all the characters with details EN version.

Returns:

Type Description
ResultT[list[Character]]

Result containing list[Character] on success or error data on error.

Example
from barch import Client

client = Client()

result = await client.character.get_all_characters()

if result.is_success:
    characters = result.value

if result.is_error:
    error = result.error

await client.close()
Source code in barch\services\character.py
async def get_all_characters(self) -> ResultT[list[Character]]:
    """Get all the characters with details EN version.

    Returns:
        [`Result`][barch.Result] containing `list[Character]` on success or error data on error.

    ??? example

        ```py
        from barch import Client

        client = Client()

        result = await client.character.get_all_characters()

        if result.is_success:
            characters = result.value

        if result.is_error:
            error = result.error

        await client.close()
        ```
    """

    return await self._get_all_characters()

get_all_characters_jp async

get_all_characters_jp() -> ResultT[list[Character]]

Get all the characters with details japanese version.

Returns:

Type Description
ResultT[list[Character]]

Result containing list[Character] on success or error data on error.

Example

```py from barch import Client

client = Client()

result = await client.character.get_all_characters_jp()

if result.is_success: characters = result.value

if result.is_error: error = result.error

await client.close()

Source code in barch\services\character.py
async def get_all_characters_jp(self) -> ResultT[list[Character]]:
    """Get all the characters with details japanese version.

    Returns:
        [`Result`][barch.Result] containing `list[Character]` on success or error data on error.

    ??? example

        ```py
        from barch import Client

        client = Client()

        result = await client.character.get_all_characters_jp()

        if result.is_success:
            characters = result.value

        if result.is_error:
            error = result.error

        await client.close()
    """

    return await self._get_all_characters(is_jp=True)

get_character async

get_character(
    name: str | None = None, id: int | None = None
) -> ResultT[CharacterDetails]

Get a single character either by name or id, EN version. Atleast one parameter, either name or id need to be specified.

Other Parameters:

Name Type Description
name str | None

The optional name of the character.

id int | None

The optional id of the character.

Returns:

Type Description
ResultT[CharacterDetails]

Result containing CharacterDetails] on success or error data on error.

Raises:

Type Description
ValueError

When no arguments are given

Example
from barch import Client

client = Client()

result = await client.character.get_character(id=10000)

if result.is_success:
    characters = result.value

if result.is_error:
    error = result.error

await client.close()
Source code in barch\services\character.py
async def get_character(
    self, name: str | None = None, id: int | None = None
) -> ResultT[CharacterDetails]:
    """Get a single character either by name or id, EN version.
    Atleast one parameter, either name or id need to be specified.

    Keyword Args:
        name: The optional name of the character.
        id: The optional id of the character.

    Returns:
        [`Result`][barch.Result] containing `CharacterDetails]` on success or error data on error.

    Raises:
        ValueError: When no arguments are given

    ??? example

        ```py
        from barch import Client

        client = Client()

        result = await client.character.get_character(id=10000)

        if result.is_success:
            characters = result.value

        if result.is_error:
            error = result.error

        await client.close()
        ```
    """

    if name or id:
        return await self._get_character(name=name, id=id)

    else:
        raise ValueError("Atleast one parameter must be specified.")

get_character_by_query async

get_character_by_query(
    role: Role | None = None,
    type: str | None = None,
    school: str | None = None,
    club: str | None = None,
    position: Position | None = None,
    weapon: str | None = None,
    damage: str | None = None,
    armor: str | None = None,
) -> ResultT[Characters]

Get a single character details based on different parameters. Atleast one parameter must be specified. Multiple parameters can be specified to get characters based on different filters.

Other Parameters:

Name Type Description
role Role | None

The optional Role enum parameter, which gets characters by role.

type str | None

The optional type parameter, which gets characters by the type.

school str | None

The optional school parameter, which gets characters by their school.

club str | None

The optional club parameter, which gets characters by their club.

position Position | None

The optional Position enum parameter, which gets characters by their position.

weapon str | None

The optional weapon parameter, which gets characters by their weapon.

damage str | None

The optional damage parameter.

armor str | None

The optional armor parameter.

Returns:

Type Description
ResultT[Characters]

Result containing Characters on success or error data on error.

Raises:

Type Description
ValueError

When no arguments are given.

Example

```py from barch import Client, Role, Position

client = Client()

result = await client.character.get_character_by_query(role=Role.Dealer, position=Position.Back)

if result.is_success: characters = result.value

if result.is_error: error = result.error

await client.close()

Source code in barch\services\character.py
async def get_character_by_query(
    self,
    role: Role | None = None,
    type: str | None = None,
    school: str | None = None,
    club: str | None = None,
    position: Position | None = None,
    weapon: str | None = None,
    damage: str | None = None,
    armor: str | None = None,
) -> ResultT[Characters]:
    """Get a single character details based on different parameters.
    Atleast one parameter must be specified. Multiple parameters can be specified
    to get characters based on different filters.

    Keyword Args:
        role: The optional `Role` enum parameter, which gets characters by role.
        type: The optional `type` parameter, which gets characters by the type.
        school: The optional `school` parameter, which gets characters by their school.
        club: The optional `club` parameter, which gets characters by their club.
        position: The optional `Position` enum parameter, which gets characters by their position.
        weapon: The optional `weapon` parameter, which gets characters by their weapon.
        damage: The optional `damage` parameter.
        armor: The optional `armor` parameter.

    Returns:
        [`Result`][barch.Result] containing `Characters` on success or error data on error.

    Raises:
        ValueError: When no arguments are given.

    ??? example

        ```py
        from barch import Client, Role, Position

        client = Client()

        result = await client.character.get_character_by_query(role=Role.Dealer, position=Position.Back)

        if result.is_success:
            characters = result.value

        if result.is_error:
            error = result.error

        await client.close()
    """

    if any([role, type, school, club, position, weapon, damage, armor]):
        params = {
            "role": role.value if role else "",
            "type": type if type else "",
            "school": school if school else "",
            "club": club if club else "",
            "position": position.value if position else "",
            "weapon": weapon if weapon else "",
            "damage": damage if damage else "",
            "armor": armor if armor else "",
        }

        route = endpoints.GET_CHARACTER_QUERY.generate_route().with_params(params)
        result = await self._http.fetch(route)

        if isinstance(result, HttpErrorResponse):
            return Error(result)

        return Success(
            [
                self._serializer.deserialize_characters_from_query(char)
                for char in result.data
            ]
        )

    else:
        raise ValueError("Atleast one parameter must be specified.")

get_character_jp async

get_character_jp(
    name: str | None = None, id: int | None = None
) -> ResultT[CharacterDetails]

Get a single character either by name or id, JP version. Atleast one parameter, either name or id need to be specified.

Other Parameters:

Name Type Description
name str | None

The optional name of the character. Note that the character input name needs to be JP.

id int | None

The optional id of the character.

Returns:

Type Description
ResultT[CharacterDetails]

Result containing CharacterDetails on success or error data on error.

Example
from barch import Client

client = Client()

result = await client.character.get_character_jp(id=10000)

if result.is_success:
    characters = result.value

if result.is_error:
    error = result.error

await client.close()
Source code in barch\services\character.py
async def get_character_jp(
    self, name: str | None = None, id: int | None = None
) -> ResultT[CharacterDetails]:
    """Get a single character either by name or id, JP version.
    Atleast one parameter, either name or id need to be specified.

    Keyword Args:
        name: The optional name of the character. Note that the character input name needs to be JP.
        id: The optional id of the character.

    Returns:
        [`Result`][barch.Result] containing `CharacterDetails` on success or error data on error.

    ??? example

        ```py
        from barch import Client

        client = Client()

        result = await client.character.get_character_jp(id=10000)

        if result.is_success:
            characters = result.value

        if result.is_error:
            error = result.error

        await client.close()
        ```"""

    return await self._get_character(name=name, id=id, is_jp=True)

HttpService

The HTTP service that is used to make requets to API.

Source code in barch\services\http.py
class HttpService:
    """The HTTP service that is used to make requets to API."""

    __slots__ = ("_session",)

    def __init__(self) -> None:
        self._session = aiohttp.ClientSession()

    def _get_session_method(self, method: str, session: Any) -> Any:
        """Get the session with method type.

        Returns:
            The session with respective method.
        """

        _method_mapping = {
            "GET": session.get,
            "POST": session.post,
            "PUT": session.put,
            "PATCH": session.patch,
            "DELETE": session.delete,
        }

        return _method_mapping[method]

    async def _request(
        self,
        session: Any,
        uri: str,
        params: dict[str, str | int],
        data: dict[str, str | int],
    ) -> HttpSuccessResponse | HttpErrorResponse:
        """Make the actual request to the MAL API based on given params.

        Returns:
            The response from the API call."""

        try:
            async with session(uri, params=params, data=data) as r:
                response = await r.json()
                if r.status == 200:
                    return HttpSuccessResponse(r.status, "Success.", response)

                return HttpErrorResponse(r.status, response.get("error"))

        except Exception as e:
            return HttpErrorResponse(500, str(e))

    async def fetch(
        self, route: GenerateRoute
    ) -> HttpSuccessResponse | HttpErrorResponse:
        """Makes a request to the given route.

        Returns:
            The HTTP response [`HttpSuccessResponse`] or [`HttpErrorResponse`] of the API call.
        """
        try:
            return await self._request(
                self._get_session_method(route.method, self._session),
                route.uri,
                route.params,
                route.data,
            )

        except Exception as e:
            return HttpErrorResponse(500, str(e))

    async def close(self) -> None:
        """Close the open aiohttp clientsession."""

        if self._session and not self._session.closed:
            await self._session.close()

close async

close() -> None

Close the open aiohttp clientsession.

Source code in barch\services\http.py
async def close(self) -> None:
    """Close the open aiohttp clientsession."""

    if self._session and not self._session.closed:
        await self._session.close()

fetch async

fetch(
    route: GenerateRoute,
) -> HttpSuccessResponse | HttpErrorResponse

Makes a request to the given route.

Returns:

Type Description
HttpSuccessResponse | HttpErrorResponse

The HTTP response [HttpSuccessResponse] or [HttpErrorResponse] of the API call.

Source code in barch\services\http.py
async def fetch(
    self, route: GenerateRoute
) -> HttpSuccessResponse | HttpErrorResponse:
    """Makes a request to the given route.

    Returns:
        The HTTP response [`HttpSuccessResponse`] or [`HttpErrorResponse`] of the API call.
    """
    try:
        return await self._request(
            self._get_session_method(route.method, self._session),
            route.uri,
            route.params,
            route.data,
        )

    except Exception as e:
        return HttpErrorResponse(500, str(e))

RaidService

Bases: BaseService

The service that handles all the methods related to raids.

Source code in barch\services\raid.py
class RaidService(BaseService):
    """The service that handles all the methods related to raids."""

    __slots__ = ()

    async def _get_raids(self, is_jp: bool = False) -> ResultT[list[Raids]]:
        """Internal method for getting raid details which is used by both EN and JP version.

        Keyword Args:
            is_jp: The optional boolean flag, which specifies if the raid details need to 
                be fetched for the EN or JP version.

        Returns:
            [`Result`][barch.Result] containing `list[Raids]` on success or error data on error.
        """

        if is_jp:
            route = endpoints.GET_RAIDS_JP.generate_route()
        else:
            route = endpoints.GET_RAIDS.generate_route()
        result = await self._http.fetch(route)

        if isinstance(result, HttpErrorResponse):
            return Error(result)

        return Success(self._serializer.deserialize_raids(result.data))

    async def get_raids(self) -> ResultT[list[Raids]]:
        """Gets all the current, upcoming and ended raid details EN version.

        Returns:
            [`Result`][barch.Result] containing `list[Raids]` on success or error data on error.
        """

        return await self._get_raids()

    async def get_raids_jp(self) -> ResultT[list[Raids]]:
        """Gets all the current, upcoming and ended raid details JP version.

        Returns:
            [`Result`][barch.Result] containing `list[Raids]` on success or error data on error.
        """

        return await self._get_raids(is_jp=True)

get_raids async

get_raids() -> ResultT[list[Raids]]

Gets all the current, upcoming and ended raid details EN version.

Returns:

Type Description
ResultT[list[Raids]]

Result containing list[Raids] on success or error data on error.

Source code in barch\services\raid.py
async def get_raids(self) -> ResultT[list[Raids]]:
    """Gets all the current, upcoming and ended raid details EN version.

    Returns:
        [`Result`][barch.Result] containing `list[Raids]` on success or error data on error.
    """

    return await self._get_raids()

get_raids_jp async

get_raids_jp() -> ResultT[list[Raids]]

Gets all the current, upcoming and ended raid details JP version.

Returns:

Type Description
ResultT[list[Raids]]

Result containing list[Raids] on success or error data on error.

Source code in barch\services\raid.py
async def get_raids_jp(self) -> ResultT[list[Raids]]:
    """Gets all the current, upcoming and ended raid details JP version.

    Returns:
        [`Result`][barch.Result] containing `list[Raids]` on success or error data on error.
    """

    return await self._get_raids(is_jp=True)