### Fetch Seller Profile Request Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs a GET request to retrieve a seller's profile information. Includes user ID and format parameters. ```python def _profile(self, id_: str) -> Request: req = Request( "GET", "https://api.mercari.jp/users/get_profile", params={"user_id": id_, "_user_format": "profile"}, headers=self._headers, ) return self._sign_request(req) ``` -------------------------------- ### Prepare Item Request Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs an HTTP GET request to fetch details for a specific item. It sets the correct API endpoint and includes the item ID in the request. ```python def _item(self, id_: str) -> Request: req = Request( "GET", "https://api.mercari.jp/items/get", ``` -------------------------------- ### Fetch Seller Profile Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Get the profile information for a specific seller using their user ID. Returns None if the profile is not found (status code 404). ```python profile = await mercapi.profile("1234567890") if profile: print(profile.name) ``` -------------------------------- ### Get a list of models Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a list of dictionaries by key and maps each item to a specified model class. ```python @staticmethod def get_list_of_model(key: str, model: Type[M]) -> ExtractorDef[List[M]]: if type(model) == str: model = Extractors.__import_class(model) return lambda x: [map_to_class(i, model) for i in x[key]] if key in x else None ``` -------------------------------- ### Search for Items Source: https://take-kun.github.io/mercapi/mercapi.html Performs a search query and prints the number of found results and details of each item. Requires the Mercapi package to be installed. ```python from mercapi import Mercapi m = Mercapi() results = await m.search('sharpnel') print(f'Found {results.meta.num_found} results') for item in results.items: print(f'Name: {item.name}\nPrice: {item.price}\n') ``` -------------------------------- ### Get a value and map to a model Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a dictionary by key and maps it to a specified model class. Supports optional mapping definitions. ```python @staticmethod def get_as_model( key: str, model: Type[M], map_def: Optional[ResponseMappingDefinition] = None ) -> ExtractorDef[M]: if type(model) == str: model = Extractors.__import_class(model) return lambda x: map_to_class(x[key], model, map_def) if key in x else None ``` -------------------------------- ### Get Seller Items Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetches all items currently sold by a specified seller. Returns None if the seller is not found. ```APIDOC ## GET /items/get_items ### Description Fetches all items currently sold by a specified seller. Returns `None` if the seller is not found (404). ### Method GET ### Endpoint https://api.mercari.jp/items/get_items ### Parameters #### Query Parameters - **seller_id** (string) - Required - The ID of the seller whose items are to be fetched. - **limit** (integer) - Optional - The maximum number of items to return. Defaults to 30. - **status** (string) - Optional - A comma-separated string of item statuses to filter by (e.g., "on_sale,trading,sold_out"). Defaults to "on_sale,trading,sold_out". ### Response #### Success Response (200) - **Items** (Items) - An object containing a list of items sold by the specified seller. #### Error Response (404) - Returns `None`. #### Response Example ```json { "example": "Items object" } ``` ``` -------------------------------- ### Get Seller Profile Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetches the details of a single seller (profile) by their ID. Returns None if the profile is not found. ```APIDOC ## GET /users/get_profile ### Description Fetches details of a single seller (profile) by their unique identifier. Returns `None` if the profile is not found (404). ### Method GET ### Endpoint https://api.mercari.jp/users/get_profile ### Parameters #### Query Parameters - **user_id** (string) - Required - The unique identifier of the seller (profile) to fetch. - **_user_format** (string) - Required - Specifies the format of the user data, expected to be 'profile'. ### Response #### Success Response (200) - **Profile** (Profile) - An object containing all available properties of the seller's profile. #### Error Response (404) - Returns `None`. #### Response Example ```json { "example": "Profile object" } ``` ``` -------------------------------- ### Fetch All Items by Seller Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Retrieves a list of all items sold by a specified seller using their profile ID. This method simulates loading the single seller profile view to get their items. ```python async def items(self, profile_id: str) -> Optional[Items]: """Fetch all items sold by specified seller. This method reflects the action of loading single seller profile view. :param profile_id: ID of a seller :return: list of items sold by specified seller """ res = await self._client.send(self._items(profile_id)) if res.status_code == 404: return None body = res.json() return map_to_class(body, Items) ``` -------------------------------- ### Fetch Seller Items Request Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs a GET request to retrieve all items listed by a specific seller. Supports filtering by sale status and limits the number of results. ```python def _items(self, profile_id: str) -> Request: req = Request( "GET", "https://api.mercari.jp/items/get_items", params={ "seller_id": profile_id, "limit": 30, "status": "on_sale,trading,sold_out", }, headers=self._headers, ) return self._sign_request(req) ``` -------------------------------- ### Get Item Details Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetches the details of a single listing (item) by its ID. Returns None if the item is not found. ```APIDOC ## GET /items/get ### Description Fetches details of a single listing (item) by its unique identifier. Returns `None` if the item is not found (404). ### Method GET ### Endpoint https://api.mercari.jp/items/get ### Parameters #### Query Parameters - **id** (string) - Required - The unique identifier of the item to fetch. ### Response #### Success Response (200) - **Item** (Item) - An object containing all available properties of the listing. #### Error Response (404) - Returns `None`. #### Response Example ```json { "example": "Item object" } ``` ``` -------------------------------- ### Get a list of values and apply a mapper Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a list by key and applies a mapper function to each item in the list. Returns None if the key is not found. ```python @staticmethod def get_list_with(key: str, mapper: Callable[[Any], T]) -> ExtractorDef[List[T]]: return lambda x: [mapper(i) for i in x[key]] if key in x else None ``` -------------------------------- ### Get a datetime value Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a value by key, converts it to a float, and then to a datetime object using fromtimestamp. ```python @staticmethod def get_datetime(key: str) -> ExtractorDef[datetime]: return Extractors.get_with(key, lambda x: datetime.fromtimestamp(float(x))) ``` -------------------------------- ### Get Full Item Details from Summary Source: https://take-kun.github.io/mercapi/mercapi.html Fetches the complete details for an item using an item summary object obtained from a search. This allows for retrieving more information after an initial search. ```APIDOC ## Get Full Item Details from Summary ### Description Retrieves the full details of a Mercari listing from an existing item summary object. ### Method ``` item_summary.full_item() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'results' is the response from m.search() item = results.items[0] full_item_details = await item.full_item() ``` ### Response - **full_item_details** (object) - An object containing all details of the Mercari listing. ``` -------------------------------- ### Get a value and apply a mapper function Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a value by key and applies a custom mapper function to it. Returns None if the key is not found. ```python @staticmethod def get_with(key: str, mapper: Callable[[S], T]) -> ExtractorDef[T]: return lambda x: mapper(x[key]) if key in x else None ``` -------------------------------- ### Retrieve Full Item Details from Search Results Source: https://take-kun.github.io/mercapi After performing a search, use this snippet to get the complete details of a specific item from the search results. ```python item = results.items[0] full_item = await item.full_item() print(full_item.description) ``` -------------------------------- ### Get a value and cast to type Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a value by key and attempts to cast it to a specified type. Returns None if the key is not found. ```python @staticmethod def get_as(key: str, type_: Type[S]) -> ExtractorDef[S]: return lambda x: type_(x[key]) if key in x else None ``` -------------------------------- ### Get Item Directly by ID Source: https://take-kun.github.io/mercapi/mercapi.html Fetches the full details of an item directly using its unique ID. This is an alternative to searching and then retrieving full details. ```python item = await m.item('m90925725213') print(item.description) ``` -------------------------------- ### Initialize Mercapi Client Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Instantiate the main Mercapi class. A random key-pair is generated for signing requests. Avoid instantiating this class more than once per runtime. ```python from mercapi import Mercapi mercapi = Mercapi() ``` -------------------------------- ### Creating a ResponseProperty Instance Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Illustrates how to instantiate the ResponseProperty class. This is used to declare a specific mapping rule for a single property. ```python ResponseProperty(raw_property_name, model_property_name, extractor) ``` -------------------------------- ### Mercapi Class Initialization Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Initializes the Mercapi client. A random key-pair is generated for signing requests. Proxies and User-Agent can be optionally configured. ```python import random import uuid from typing import Optional, List import httpx from httpx._types import ProxiesTypes from ecdsa import SigningKey, NIST256p from httpx import Request from mercapi.mapping import map_to_class from mercapi.models import SearchResults, Item, Profile, Items from mercapi.models.base import ResponseModel from mercapi.requests import SearchRequestData from mercapi.util import jwt class Mercapi: """Main class of the module containing all implemented wrappers of Mercari API. A random key-pair will be generated during the class instantiation. It is used for signing all HTTP requests sent in the course of methods execution. **Avoid instantiating this class more than once in a single runtime.** """ def __init__( self, *, proxies: Optional[ProxiesTypes] = None, user_agent: Optional[str] = None, ): """initialize :param proxies: Once the proxy is configured, the IP address of the access source can be changed. (e.g. {"http://": "http://example.com:1234", "https://": "http://example.com:1234"}) :param user_agent: User-Agent """ if not user_agent: user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 " "Safari/537.3" self._headers = { "User-Agent": user_agent, "X-Platform": "web", } self._uuid = str(uuid.UUID(int=random.getrandbits(128))) self._key = SigningKey.generate(NIST256p) self._client = httpx.AsyncClient(proxies=proxies) ResponseModel.set_mercapi(self) ``` -------------------------------- ### Mercapi Class Initialization Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Initializes the Mercapi client. It generates a random key-pair for signing requests and sets default headers. Proxies and a custom User-Agent can be provided. ```python def __init__( self, *, proxies: Optional[ProxiesTypes] = None, user_agent: Optional[str] = None, ): """initialize :param proxies: Once the proxy is configured, the IP address of the access source can be changed. (e.g. {"http://": "http://example.com:1234", "https://": "http://example.com:1234"}) :param user_agent: User-Agent """ if not user_agent: user_agent = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 " "Safari/537.3" ) self._headers = { "User-Agent": user_agent, "X-Platform": "web", } self._uuid = str(uuid.UUID(int=random.getrandbits(128))) self._key = SigningKey.generate(NIST256p) self._client = httpx.AsyncClient(proxies=proxies) ResponseModel.set_mercapi(self) ``` -------------------------------- ### Mercapi Class Initialization Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Initializes the Mercapi client. A random key-pair is generated for signing HTTP requests. It's recommended to instantiate this class only once per runtime. ```APIDOC ## Mercapi Class ### Description Main class of the module containing all implemented wrappers of Mercari API. A random key-pair will be generated during the class instantiation. It is used for signing all HTTP requests sent in the course of methods execution. **Avoid instantiating this class more than once in a single runtime.** ### Parameters - **proxies** (Optional[ProxiesTypes]) - Optional - Once the proxy is configured, the IP address of the access source can be changed. (e.g. {"http://": "http://example.com:1234", "https://": "http://example.com:1234"}) - **user_agent** (Optional[str]) - Optional - User-Agent. Defaults to a Chrome User-Agent if not provided. ``` -------------------------------- ### Get a value by key Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Extracts a value from a dictionary using a specified key. Returns None if the key is not found. ```python @staticmethod def get(key: str) -> ExtractorDef[Any]: return lambda x: x.get(key) ``` -------------------------------- ### Mercapi Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Initializes the Mercapi client. A random key-pair is generated for signing HTTP requests. It's recommended to instantiate this class only once per runtime. ```APIDOC ## Mercapi ### Description Initializes the Mercapi client. A random key-pair is generated for signing HTTP requests. It's recommended to instantiate this class only once per runtime. ### Parameters #### Keyword Arguments * **proxies** (Union[ForwardRef('URL'), str, ForwardRef('Proxy'), Dict[Union[ForwardRef('URL'), str], Union[NoneType, ForwardRef('URL'), str, ForwardRef('Proxy')]], NoneType]) - Optional - Configure proxy to change the IP address of the access source. (e.g. {"http://": "http://example.com:1234", "https://": "http://example.com:1234"}) * **user_agent** (Optional[str]) - Optional - User-Agent string. ``` -------------------------------- ### Mercapi Class Initialization Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Initializes the Mercapi client. It sets default headers including User-Agent and X-Platform. A unique UUID is generated for each instance. ```python class Mercapi: """Main class of the module containing all implemented wrappers of Mercari API. A random key-pair will be generated during the class instantiation. It is used for signing all HTTP requests sent in the course of methods execution. **Avoid instantiating this class more than once in a single runtime.** """ def __init__( self, *, proxies: Optional[ProxiesTypes] = None, user_agent: Optional[str] = None, ): """initialize :param proxies: Once the proxy is configured, the IP address of the access source can be changed. (e.g. {"http://": "http://example.com:1234", "https://": "http://example.com:1234"}) :param user_agent: User-Agent """ if not user_agent: user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 " "Safari/537.3" self._headers = { "User-Agent": user_agent, "X-Platform": "web", } self._uuid = str(uuid.UUID(int=random.getrandbits(128))) ``` -------------------------------- ### Import Profile and Items Models Source: https://take-kun.github.io/mercapi/mercapi/models/profile.html Import the Profile and Items models from the mercapi library. These are essential for working with profile data. ```python from .profile import Profile from .items import Items ``` -------------------------------- ### Fetch Seller Profile Source: https://take-kun.github.io/mercapi/mercapi/models/search/search_result_item.html Asynchronously fetches the seller's profile information using the seller ID. ```python async def seller(self) -> "Profile": return await self._mercapi.profile(self.seller_id) ``` -------------------------------- ### Fetch Seller Profile Details Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Retrieves detailed information for a specific seller using their ID. This method simulates loading the single seller profile view. ```python async def profile(self, id_: str) -> Optional[Profile]: """Fetch details of a single seller. This method reflects the action of loading single seller profile view. :param id_: id of a seller (profile) :return: all available seller (profile) properties """ res = await self._client.send(self._profile(id_)) if res.status_code == 404: return None body = res.json() return map_to_class(body["data"], Profile) ``` -------------------------------- ### Import Search Models Source: https://take-kun.github.io/mercapi/mercapi/models/search.html Imports necessary data models for search operations from the mercapi library. ```python from .meta import Meta from .search_result_item import SearchResultItem from .search_results import SearchResults ``` -------------------------------- ### Internal Profile Request Construction Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs the HTTP request object for fetching a seller's profile. It signs the request before returning it. ```python def _profile(self, id_: str) -> Request: req = Request( "GET", "https://api.mercari.jp/users/get_profile", params={"user_id": id_, "_user_format": "profile"}, headers=self._headers, ) return self._sign_request(req) ``` -------------------------------- ### Create a Basic Key Extractor Source: https://take-kun.github.io/mercapi/mercapi/models/base.html Use `Extractors.get` to create a function that safely retrieves a value for a given key from a dictionary. It returns None if the key is not found. ```python @staticmethod def get(key: str) -> ExtractorDef[Any]: return lambda x: x.get(key) ``` -------------------------------- ### Get Item Details Source: https://take-kun.github.io/mercapi/mercapi.html Retrieves the full details of a specific Mercari listing using its unique ID. This method is useful for obtaining comprehensive information about an item. ```APIDOC ## Get Item Details by ID ### Description Retrieves the complete details for a specific Mercari listing using its unique item ID. ### Method ``` item(item_id: str) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from mercapi import Mercapi m = Mercapi() item_details = await m.item('m90925725213') ``` ### Response - **item_details** (object) - An object containing all details of the Mercari listing, such as description, price, images, etc. ``` -------------------------------- ### Define Seller Photo URL Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'photo_url' field to 'photo' for the Seller model. ```python ResponseProperty("photo_url", "photo", Extractors.get("photo_url")) ``` -------------------------------- ### Fetch All Items by Seller Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Retrieve a list of all items currently or previously sold by a specified seller. Returns None if the seller is not found (status code 404). ```python items = await mercapi.items("1234567890") if items: print(items.data[0].name) ``` -------------------------------- ### Fetch Full Item Details Source: https://take-kun.github.io/mercapi/mercapi/models/search/search_result_item.html Asynchronously fetches the complete details of the item using its ID. ```python async def full_item(self) -> "Item": return await self._mercapi.item(self.id_) ``` -------------------------------- ### Define Seller Photo Thumbnail URL Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'photo_thumbnail_url' field to 'photo_thumbnail' for the Seller model. ```python ResponseProperty( "photo_thumbnail_url", "photo_thumbnail", Extractors.get("photo_thumbnail_url"), ) ``` -------------------------------- ### Import mercapi Models Source: https://take-kun.github.io/mercapi/mercapi/models.html Imports necessary data models from the mercapi library for use in your application. Ensure these modules are available in your project's path. ```python from .search import SearchResults, SearchResultItem from .item import Item from .profile import Profile, Items ``` -------------------------------- ### item Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetch details of a single listing (item). This method reflects the action of loading a single item view. ```APIDOC ## GET /api/v1/items/{id} ### Description Fetch details of a single listing (item). ### Method GET ### Endpoint /api/v1/items/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the listing (item). ### Response #### Success Response (200) - **data** (object) - Contains the item details. #### Response Example { "data": { "item_id": "string", "name": "string", "description": "string" } } ``` -------------------------------- ### Define Shipping Class Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps shipping class properties including 'id', 'fee', 'icon_id', 'pickup_fee', 'shipping_fee', 'total_fee', and 'is_pickup' using `Extractors.get`. ```python ShippingClass: R( required_properties=[ ResponseProperty("id", "id_", Extractors.get("id")), ResponseProperty("fee", "fee", Extractors.get("fee")), ResponseProperty("icon_id", "icon_id", Extractors.get("icon_id")), ResponseProperty("pickup_fee", "pickup_fee", Extractors.get("pickup_fee")), ResponseProperty("shipping_fee", "shipping_fee", Extractors.get("shipping_fee")), ResponseProperty("total_fee", "total_fee", Extractors.get("total_fee")), ResponseProperty("is_pickup", "is_pickup", Extractors.get("is_pickup")), ], optional_properties=[], ) ``` -------------------------------- ### Prepare Search Request Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs an HTTP POST request for the Mercari search API. It serializes the search request data into JSON and includes necessary headers, then signs the request. ```python def _search(self, search_request_data: SearchRequestData) -> Request: req = Request( "POST", "https://api.mercari.jp/v2/entities:search", json=search_request_data.data, headers=self._headers, ) return self._sign_request(req) ``` -------------------------------- ### Parse API Response and Instantiate Model Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html This code snippet demonstrates the process of parsing an API response and instantiating a model class based on a provided mapping definition. It handles required properties by extracting them using defined extractors and raises an error if any required property is missing or cannot be extracted. Optional properties are also extracted, with errors during extraction being reported but not halting the process. The function returns an instance of the specified class populated with the extracted properties. ```python 670 "map_to_class() is supposed to be called with ResponseModel subclass as a parameter" 671 ) 672 673 if mapping_definition is None: 674 mapping_definition = mapping_definitions.get(clazz) 675 if mapping_definition is None: 676 raise ValueError(f"Mapping definition is not provided for {clazz.__name__}") 677 678 init_properties = {} 679 680 for prop in mapping_definition.required_properties: 681 try: 682 raw_prop = prop.extractor(response) 683 if raw_prop is None: 684 raise ValueError("Extractor returned None value") 685 init_properties[prop.model_property_name] = raw_prop 686 except Exception as exc: 687 raise ParseAPIResponseError( 688 f"Failed to retrieve required {clazz.__name__} property {prop.raw_property_name} from the response" 689 ) from exc 690 691 for prop in mapping_definition.optional_properties: 692 raw_prop = None 693 try: 694 raw_prop = prop.extractor(response) 695 except Exception as exc: 696 _report_incorrect_optional(prop.raw_property_name, response, exc) 697 init_properties[prop.model_property_name] = raw_prop 698 699 return clazz(**init_properties) ``` -------------------------------- ### profile Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetch details of a single seller. This method reflects the action of loading a single seller profile view. ```APIDOC ## profile ### Description Fetch details of a single seller. This method reflects the action of loading a single seller profile view. ### Parameters #### Path Parameters * **id_** (str) - Required - ID of a seller (profile). ### Return Value * Optional[Profile] - All available seller (profile) properties, or None if not found. ``` -------------------------------- ### profile Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetch details of a single seller. This method reflects the action of loading a single seller profile view. ```APIDOC ## GET /api/v1/users/{id} ### Description Fetch details of a single seller. ### Method GET ### Endpoint /api/v1/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the seller (profile). ### Response #### Success Response (200) - **data** (object) - Contains the seller profile details. #### Response Example { "data": { "user_id": "string", "name": "string", "description": "string" } } ``` -------------------------------- ### items Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetch all items sold by a specified seller. This method reflects the action of loading a single seller profile view. ```APIDOC ## items ### Description Fetch all items sold by a specified seller. This method reflects the action of loading a single seller profile view. ### Parameters #### Path Parameters * **profile_id** (str) - Required - ID of a seller. ### Return Value * Optional[Items] - A list of items sold by the specified seller, or None if not found. ``` -------------------------------- ### items Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetch all items sold by a specified seller. This method reflects the action of loading a single seller profile view. ```APIDOC ## GET /api/v1/users/{profile_id}/items ### Description Fetch all items sold by a specified seller. ### Method GET ### Endpoint /api/v1/users/{profile_id}/items ### Parameters #### Path Parameters - **profile_id** (string) - Required - The ID of the seller. ### Response #### Success Response (200) - **items** (array) - A list of items sold by the specified seller. #### Response Example { "items": [ { "item_id": "string", "name": "string" } ] } ``` -------------------------------- ### Base ResponseModel Class Source: https://take-kun.github.io/mercapi/mercapi/models/base.html Provides a base class for all response models, with a static method to set the mercapi instance. ```python class ResponseModel: _mercapi: "Mercapi" @classmethod def set_mercapi(cls, mercapi: "Mercapi") -> None: cls._mercapi = mercapi ``` -------------------------------- ### Internal Item Request Construction Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs the HTTP request object for fetching a single item's details. It signs the request before returning it. ```python def _item(self, id_: str) -> Request: req = Request( "GET", "https://api.mercari.jp/items/get", params={"id": id_}, headers=self._headers, ) return self._sign_request(req) ``` -------------------------------- ### item Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Fetches the details of a single listing (item) by its ID. This method corresponds to viewing an individual item's page. ```APIDOC ## GET https://api.mercari.jp/items/get ### Description Fetches the details of a single listing (item) by its ID. ### Method GET ### Endpoint https://api.mercari.jp/items/get ### Parameters #### Query Parameters - **id_** (string) - Required - The ID of the listing (item) to fetch. ### Response #### Success Response (200) - **data** (Item) - Contains all available properties of the listing (item). #### Response Example { "data": { "id": "string", "name": "string", "price": "string", "currency": "string" } } #### Error Response (404) - Returns `None` if the item is not found. ``` -------------------------------- ### Fetch Full Item Details Source: https://take-kun.github.io/mercapi/mercapi/models/profile/items.html Method to retrieve complete details for a specific item using its ID. This is equivalent to calling the main `mercapi.Mercapi.item` function. ```python async def full_item(self) -> Item: """Fetch full details of a listing (item). Equivalent of :func:`~mercapi.Mercapi.item` """ return await self._mercapi.item(self.id_) ``` -------------------------------- ### Define Offerable V2 Status Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'is_offerable_v2' field using a simple extractor. ```python ResponseProperty( "is_offerable_v2", "is_offerable_v2", Extractors.get("is_offerable_v2") ) ``` -------------------------------- ### Create an Extractor with a Custom Mapper Source: https://take-kun.github.io/mercapi/mercapi/models/base.html Use `Extractors.get_with` to create a function that retrieves a value for a given key and applies a custom mapping function to it. Returns None if the key is not found. ```python @staticmethod def get_with(key: str, mapper: Callable[[S], T]) -> ExtractorDef[T]: return lambda x: mapper(x[key]) if key in x else None ``` -------------------------------- ### Define Seller Name Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'name' field to 'name' for the Seller model. ```python ResponseProperty("name", "name", Extractors.get("name")) ``` -------------------------------- ### Internal Items Request Construction Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs the HTTP request object for fetching all items sold by a seller. It includes default parameters for limit and status and signs the request. ```python def _items(self, profile_id: str) -> Request: req = Request( "GET", "https://api.mercari.jp/items/get_items", params={ "seller_id": profile_id, "limit": 30, "status": "on_sale,trading,sold_out", }, headers=self._headers, ) return self._sign_request(req) ``` -------------------------------- ### Fetch Single Item Details Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Retrieves detailed information for a specific listing (item) using its ID. This method simulates loading the single item view. ```python async def item(self, id_: str) -> Optional[Item]: """Fetch details of a single listing (item). This method reflects the action of loading single item view. :param id_: id of a listing (item) :return: all available listing (item) properties """ res = await self._client.send(self._item(id_)) if res.status_code == 404: return None body = res.json() return map_to_class(body["data"], Item) ``` -------------------------------- ### Profile Dataclass (Alternative View) Source: https://take-kun.github.io/mercapi/mercapi/models/profile/profile.html An alternative view of the Profile dataclass definition, highlighting its structure and attributes. ```python @dataclass class Profile(ResponseModel): @dataclass class Ratings(ResponseModel): good: int normal: int bad: int @dataclass class PolarizedRatings(ResponseModel): good: int bad: int id_: str name: str photo_url: str photo_thumbnail_url: str register_sms_confirmation: str ratings: Ratings polarized_ratings: PolarizedRatings num_ratings: int star_rating_score: int is_followable: bool is_blocked: bool following_count: int follower_count: int score: int created: datetime proper: bool introduction: str is_official: bool num_sell_items: int num_ticket: int bounce_mail_flag: str current_point: int current_sales: int is_organizational_user: bool async def items(self) -> "Items": return await self._mercapi.items(self.id_) ``` -------------------------------- ### Create an Extractor for a ResponseModel Source: https://take-kun.github.io/mercapi/mercapi/models/base.html Use `Extractors.get_as_model` to create a function that retrieves a dictionary for a given key and attempts to parse it into a specified `ResponseModel` subclass. Handles string class names by importing them. ```python @staticmethod def get_as_model(key: str, model: Type[M]) -> ExtractorDef[M]: if type(model) == str: model = Extractors.__import_class(model) return lambda x: model.from_dict(x[key]) if key in x else None ``` -------------------------------- ### Import Request Data Structures Source: https://take-kun.github.io/mercapi/mercapi/requests.html Imports base and search request data classes from the mercapi library. These are fundamental for constructing API requests. ```python from .base import RequestData from .search import SearchRequestData ``` -------------------------------- ### Fetch Previous Page of Search Results Source: https://take-kun.github.io/mercapi/mercapi/models/search/search_results.html Retrieves the previous page of search results. Raises an error if already on the first page. ```python async def prev_page(self) -> "SearchResults": if self.meta.prev_page_token == "": raise IncorrectRequestError( "Cannot fetch previous page of search results, you are probably on the first page" ) new_request = copy(self._request) new_request.page_token = self.meta.prev_page_token return await self._mercapi._search_impl(new_request) ``` -------------------------------- ### Fetch Next Page of Search Results Source: https://take-kun.github.io/mercapi/mercapi/models/search/search_results.html Retrieves the next page of search results. Raises an error if already on the last page. ```python async def next_page(self) -> "SearchResults": if self.meta.next_page_token == "": raise IncorrectRequestError( "Cannot fetch new page of search results, you are probably on the last page" ) new_request = copy(self._request) new_request.page_token = self.meta.next_page_token return await self._mercapi._search_impl(new_request) ``` -------------------------------- ### Define Seller SMS Confirmation Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'register_sms_confirmation' field for the Seller model. ```python ResponseProperty( "register_sms_confirmation", "register_sms_confirmation", Extractors.get("register_sms_confirmation"), ) ``` -------------------------------- ### Define Offerable Status Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'is_offerable' field using a simple extractor. ```python ResponseProperty( "is_offerable", "is_offerable", Extractors.get("is_offerable") ) ``` -------------------------------- ### Profile Items Method Source: https://take-kun.github.io/mercapi/mercapi/models/profile/profile.html Asynchronous method within the Profile model to fetch associated items using the profile's ID. ```python async def items(self) -> "Items": return await self._mercapi.items(self.id_) ``` -------------------------------- ### Define Seller Properties Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps various seller properties including 'id', 'name', 'created', 'num_sell_items', 'ratings', 'num_ratings', 'score', 'is_official', 'quick_shipper', and 'star_rating_score'. Includes specific extraction logic for 'register_sms_confirmation_at' and nested 'ratings' model. ```python Seller: R( required_properties=[ ResponseProperty("id", "id_", Extractors.get("id")), ResponseProperty("name", "name", Extractors.get("name")), ResponseProperty( "register_sms_confirmation_at", "register_sms_confirmation_at", Extractors.get_with( "register_sms_confirmation_at", lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"), ), ), ResponseProperty("created", "created", Extractors.get_datetime("created")), ResponseProperty("num_sell_items", "num_sell_items", Extractors.get("num_sell_items")), ResponseProperty("ratings", "ratings", Extractors.get_as_model("ratings", Seller.Ratings)), ResponseProperty("num_ratings", "num_ratings", Extractors.get("num_ratings")), ResponseProperty("score", "score", Extractors.get("score")), ResponseProperty("is_official", "is_official", Extractors.get("is_official")), ResponseProperty("quick_shipper", "quick_shipper", Extractors.get("quick_shipper")), ResponseProperty("star_rating_score", "star_rating_score", Extractors.get("star_rating_score")), ], optional_properties=[], ) ``` -------------------------------- ### Items Data Model Source: https://take-kun.github.io/mercapi/mercapi/models/profile/items.html A container model for a list of `SellerItem` objects. This is typically returned when a request yields multiple item profiles. ```python @dataclass class Items(ResponseModel): items: List[SellerItem] ``` -------------------------------- ### Define Response Properties for User Profile Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Defines required and optional properties for a user profile, specifying how each field is extracted and its expected type. ```python ResponseProperty("proper", "proper", Extractors.get("proper")), ResponseProperty( "introduction", "introduction", Extractors.get("introduction") ), ResponseProperty( "is_official", "is_official", Extractors.get("is_official") ), ResponseProperty( "num_sell_items", "num_sell_items", Extractors.get("num_sell_items") ), ResponseProperty("num_ticket", "num_ticket", Extractors.get("num_ticket")), ResponseProperty( "bounce_mail_flag", "bounce_mail_flag", Extractors.get("bounce_mail_flag"), ), ResponseProperty( "current_point", "current_point", Extractors.get("current_point") ), ResponseProperty( "current_sales", "current_sales", Extractors.get("current_sales") ), ResponseProperty( "is_organizational_user", "is_organizational_user", Extractors.get("is_organizational_user"), ) ``` -------------------------------- ### Define Shipping Method Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'shipping_method' field to the ShippingMethod model. ```python ResponseProperty( "shipping_method", "shipping_method", Extractors.get_as_model("shipping_method", ShippingMethod), ) ``` -------------------------------- ### Set Mercapi Instance for ResponseModel Source: https://take-kun.github.io/mercapi/mercapi/models/base.html Class method to set the Mercapi instance associated with the ResponseModel. This is typically called once during Mercapi initialization. ```python class ResponseModel: _mercapi: "Mercapi" @classmethod def set_mercapi(cls, mercapi: "Mercapi") -> None: cls._mercapi = mercapi ``` -------------------------------- ### Create an Extractor for a List with Custom Mappers Source: https://take-kun.github.io/mercapi/mercapi/models/base.html Use `Extractors.get_list_with` to create a function that retrieves a list for a given key and applies a custom mapping function to each item in the list. Returns None if the key is not found. ```python @staticmethod def get_list_with(key: str, mapper: Callable[[Any], T]) -> ExtractorDef[List[T]]: return lambda x: [mapper(i) for i in x[key]] if key in x else None ``` -------------------------------- ### Define Shipping Method Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps shipping method properties 'id', 'name', and optionally 'is_deprecated' using `Extractors.get`. ```python ShippingMethod: R( required_properties=[ ResponseProperty("id", "id_", Extractors.get("id")), ResponseProperty("name", "name", Extractors.get("name")), ], optional_properties=[ ResponseProperty("is_deprecated", "is_deprecated", Extractors.get("is_deprecated")), ], ) ``` -------------------------------- ### Item Model Definition Source: https://take-kun.github.io/mercapi/mercapi/models/item/item.html Defines the Item data class, inheriting from ResponseModel. This class structures the data received for an item listing, including its unique identifier, seller information, name, price, description, photos, categories, condition, shipping preferences, and various boolean flags indicating its status and features. ```python from dataclasses import dataclass from datetime import datetime from typing import List from mercapi.models.base import ResponseModel from mercapi.models.common import ItemCategorySummary from mercapi.models.item.data import ( ItemCondition, ShippingFromArea, ShippingMethod, ShippingDuration, ShippingClass, ShippingPayer, Color, Seller, Comment, ) @dataclass class Item(ResponseModel): id_: str seller: Seller status: str name: str price: int description: str photos: List[str] photo_paths: List[str] thumbnails: List[str] item_category: ItemCategorySummary item_condition: ItemCondition colors: List[Color] shipping_payer: ShippingPayer shipping_method: ShippingMethod shipping_from_area: ShippingFromArea shipping_duration: ShippingDuration shipping_class: ShippingClass num_likes: int num_comments: int comments: List[Comment] updated: datetime created: datetime pager_id: int liked: bool checksum: str is_dynamic_shipping_fee: bool application_attributes: dict is_shop_item: str is_anonymous_shipping: bool is_web_visible: bool is_offerable: bool is_organizational_user: bool organizational_user_status: str is_stock_item: bool is_cancelable: bool shipped_by_worker: bool has_additional_service: bool has_like_list: bool is_offerable_v2: bool ``` -------------------------------- ### Define Response Properties for Search Results Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Defines required properties for search results, including metadata and a list of items. It specifies how to extract and model these fields. ```python ResponseProperty("meta", "meta", Extractors.get_as_model("meta", Meta)), ResponseProperty( "items", "items", Extractors.get_list_of_model("items", SearchResultItem), ) ``` -------------------------------- ### Define Response Properties for Meta Information Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Defines required properties for meta information, such as pagination tokens and the total number of found items. It specifies extraction methods and type casting. ```python ResponseProperty( "nextPageToken", "next_page_token", Extractors.get("nextPageToken") ), ResponseProperty( "previousPageToken", "prev_page_token", Extractors.get("previousPageToken"), ), ResponseProperty( "numFound", "num_found", Extractors.get_as("numFound", int) ) ``` -------------------------------- ### Shipping Method Data Model Source: https://take-kun.github.io/mercapi/mercapi/models/item/data.html Represents a shipping method with its ID, name, and a flag indicating if it's deprecated. Use this to manage available shipping options. ```python @dataclass class ShippingMethod(ResponseModel): id_: int name: str is_deprecated: str ``` -------------------------------- ### SearchResults.prev_page Source: https://take-kun.github.io/mercapi/mercapi/models/search/search_results.html Fetches the previous page of search results. Raises an error if already on the first page. ```APIDOC ## async def prev_page() ### Description Fetches the previous page of search results. This method is useful for paginating backward through search results. ### Method Asynchronous function call ### Parameters None ### Response - **SearchResults** (SearchResults) - The previous page of search results. ### Errors - **IncorrectRequestError**: Raised if `meta.prev_page_token` is empty, indicating the first page has been reached. ``` -------------------------------- ### Define ResponseMappingDefinition Structure Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Defines the structure for mapping API responses, including lists of required and optional properties. ```python class ResponseMappingDefinition(NamedTuple): required_properties: List[ResponseProperty] optional_properties: List[ResponseProperty] ``` -------------------------------- ### Define Seller ID Mapping Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Maps the 'id' field to 'id_' for the Seller model. ```python ResponseProperty("id", "id_", Extractors.get("id")) ``` -------------------------------- ### ShippingClass Data Model Source: https://take-kun.github.io/mercapi/mercapi/models/item/data.html Defines the structure for shipping class details, including fees, icon ID, and pickup status. ```python 77@dataclass 78class ShippingClass(ResponseModel): 79 id_: int 80 fee: int 81 icon_id: int 82 pickup_fee: int 83 shipping_fee: int 84 total_fee: int 85 is_pickup: bool ``` -------------------------------- ### ShippingDuration Data Model Source: https://take-kun.github.io/mercapi/mercapi/models/item/data.html Defines the structure for shipping duration information, including ID, name, and minimum/maximum days. ```python 69@dataclass 70class ShippingDuration(ResponseModel): 71 id_: int 72 name: str 73 min_days: int 74 max_days: int ``` -------------------------------- ### Shipping Duration Data Model Source: https://take-kun.github.io/mercapi/mercapi/models/item/data.html Defines the estimated shipping time frame, including minimum and maximum delivery days. Use this to provide customers with delivery estimates. ```python @dataclass class ShippingDuration(ResponseModel): id_: int name: str min_days: int max_days: int ``` -------------------------------- ### Retrieve Full Item Details Source: https://take-kun.github.io/mercapi/mercapi.html Retrieves the full details of a specific item using a result object. This requires a prior search to obtain the result object. ```python item = results.items[0] full_item = await item.full_item() print(full_item.description) ``` -------------------------------- ### Define Optional Response Properties for Search Result Item Source: https://take-kun.github.io/mercapi/mercapi/mapping/definitions.html Defines optional properties for a search result item, covering details like seller ID, status, timestamps, and various item identifiers. ```python ResponseProperty("sellerId", "seller_id", Extractors.get("sellerId")), ResponseProperty("status", "status", Extractors.get("status")), ResponseProperty("created", "created", Extractors.get_datetime("created")), ResponseProperty("updated", "updated", Extractors.get_datetime("updated")), ResponseProperty("thumbnails", "thumbnails", Extractors.get("thumbnails")), ResponseProperty("itemType", "item_type", Extractors.get("itemType")), ResponseProperty( "itemConditionId", "item_condition_id", Extractors.get_as("itemConditionId", int), ), ResponseProperty( "shippingPayerId", "shipping_payer_id", Extractors.get_as("shippingPayerId", int), ), ResponseProperty( "shippingMethodId", "shipping_method_id", Extractors.get_as("shippingMethodId", int), ), ResponseProperty( "categoryId", "category_id", Extractors.get_as("categoryId", int), ), ResponseProperty("isNoPrice", "is_no_price", Extractors.get("isNoPrice")) ``` -------------------------------- ### Internal Search Request Construction Source: https://take-kun.github.io/mercapi/mercapi/mercapi.html Constructs the HTTP request object for the search API endpoint. It signs the request before returning it. ```python def _search(self, search_request_data: SearchRequestData) -> Request: req = Request( "POST", "https://api.mercari.jp/v2/entities:search", json=search_request_data.data, headers=self._headers, ) return self._sign_request(req) ```