python api介绍

    科技2025-02-15  11

    python api介绍

    纸板的一生 (A Life of Cardboard)

    I’ve been into card games almost my entire life and started playing Magic: The Gathering (MTG) around 2nd grade in the mid 90’s. Although it wasn’t really a hobby that made me popular with girls, I stuck with it on and off and spent many Friday nights at card shops grinding constructed tournaments and booster drafts during my teenage years. Now that I’m into programming and data science, I was excited to learn the online card game marketplace, TCGplayer.com has a free API.

    我几乎一生都在玩纸牌游戏,并在90年代中期开始玩2年级左右的Magic:The Gathering(MTG) 。 尽管这并不是真正的业余爱好,但却使我深受女孩的欢迎,但我还是坚持不懈地工作,并在星期五的许多夜晚在纸牌商店里度过了十几岁的少年,他们参加了精心设计的比赛和选秀。 现在,我开始学习编程和数据科学,很高兴学习在线纸牌游戏市场, TCGplayer.com提供了免费的API。

    This article walks you through how to connect and search the TCGplayer API using Python and the Requests Library. Complete Code can be found at the bottom!

    本文向您介绍如何使用Python和请求库连接和搜索TCGplayer API。 完整的代码可以在底部找到!

    A few cards in my Magic: The Gathering Collection 我的魔术:聚​​会收藏中的几张卡片

    获取API密钥 (Getting API Keys)

    TCGplayer is an internet marketplace for collectible items allowing users to set up stores through which they can sell their inventory online. API stands for Application Programming Interface.

    TCGplayer是可收藏物品的互联网市场,允许用户建立商店以通过其在线销售其库存。 API代表应用程序编程接口 。

    Located at api.tcgplayer.com, the TCGplayer API is a RESTful API application that interacts with the TCGplayer store site. A large number of endpoints exist that return all aspects of the catalog, find pricing information, and manage personal stores. — https://docs.tcgplayer.com/docs/welcome

    TCGplayer API位于api.tcgplayer.com上,是一个RESTful API应用程序,可与TCGplayer商店站点进行交互。 存在大量端点,这些端点返回目录的各个方面,查找价格信息并管理个人商店。 -https://docs.tcgplayer.com/docs/welcome

    To access their API, first fill out their application form:

    要访问其API,请先填写其申请表:

    使用Python使用请求访问API (Accessing the API with Requests using Python)

    Once your paperwork is accepted, a representative from TCGplayer will email you an Application Id, Public Key, and Private Key. Using the keys, it is possible to create a connection to the API using the Requests library in Python. Use Pip to install Requests as needed:

    接受文书工作后,TCGplayer的代表将通过电子邮件将应用程序ID , 公钥和私钥发送给您。 使用这些键,可以使用Python中的Requests库创建与API的连接。 根据需要使用Pip安装请求:

    python -m pip install requests

    文件config.py和管理API密钥 (File config.py & Managing API Keys)

    This project uses API keys. If you’re new to managing your keys, make sure to save them into a config.py file instead of hard-coding them in your app. API keys can be very valuable and must be protected. Add the config file to your gitignore file to prevent it from being pushed to your repo too!

    该项目使用API​​密钥 。 如果您不熟悉密钥管理,请确保将其保存到config.py文件中,而不是在应用程序中对其进行硬编码。 API密钥可能非常有价值,必须加以保护 。 将配置文件添加到您的gitignore文件中,以防止其也被推送到您的仓库中!

    使用钥匙 (Using your Keys)

    The Public Key and the Private Key are needed to create a Bearer Token. A Bearer Token basically tells the system to give access to whatever holds the token. It is generated by the Authentication server automatically.

    创建承载令牌需要使用公钥和私钥 。 承载令牌基本上告诉系统授予对持有令牌的内容的访问权限。 它是由身份验证服务器自动生成的。

    #import dependenciesimport requests#pull in api keys from config filefrom config import public_key, private_key#construct api requestresponse = requests.post( "https://api.tcgplayer.com/token",headers={ "Content-Type": "application/json", "Accept": "application/json"},data=(f"grant_type=client_credentials" f"&client_id={public_key}&" f"client_secret={private_key}") )

    Notice I use a POST request to the /token URL. I pass headers and a data payload containing the API keys into the request. The Bearer Token and metadata are returned.

    注意,我对/ token URL使用POST请求。 我将标头和包含API密钥的数据有效载荷传递到请求中。 返回承载令牌和元数据。

    Take a look at the data returned in the response using .json() or .text

    查看使用.json()或.text在响应中返回的数据

    response.json()#output# {'access_token': 'YOUR_GENERATED_TOKEN',# 'token_type': 'bearer',# 'expires_in': 1209599,# 'userName': 'YOUR_GENERATED_USERNAME',# '.issued': 'Sat, 12 Sep 2020 15:40:32 GMT',# '.expires': 'Sat, 26 Sep 2020 15:40:32 GMT'}

    Notice the Bearer Token expires. TCGplayer recommends caching the metadata and only regenerating the key when it is about to expire.

    注意,承载令牌已过期。 TCGplayer建议缓存元数据并仅在密钥即将到期时重新生成密钥。

    Now that the Bearer Token has been generated, it can be used to interact with the API.

    现在已经生成了承载令牌,可以将其用于与API进行交互。

    Save the Bearer Token to a variable:

    将不记名令牌保存到变量:

    access = response.json()['access_token']

    Pass the Bearer Token into the requests Header along with the word “bearer”. TCGplayer also wants you to include a User-Agent in the header so they can track API usage easier:

    将Bearer令牌连同单词“ bearer ”一起传递到请求标头中 。 TCGplayer还希望您在标头中包含User-Agent ,以便他们可以更轻松地跟踪API使用情况:

    headers = {"accept": "application/json", "Content-Type": "application/json",'User-Agent': 'YOUR_USER_AGENT', "Authorization": "bearer " + access}

    Pick an API endpoint to interact with. I will start with the Catalog > List All Categories API endpoint and start exploring!

    选择一个API端点进行交互。 我将从目录>列出所有类别 API端点开始,然后开始探索!

    TCGplayer.com API endpoints TCGplayer.com API端点 url = "https://api.tcgplayer.com/catalog/categories"response = requests.get(url, headers=headers)response.json()

    Notice the variable URL is the API endpoint I want to hit. I pass the URL and Headers into the GET request and return the JSON response.

    请注意,变量URL是我要命中的API端点。 我将URL和标头传递到GET请求中,并返回JSON响应。

    If I wanted to explore more about a particular category, I can use the categoryID in the URL for the API endpoint. For example, the URL below will let me search category 1 (Magic the gathering is category 1):

    如果我想进一步了解某个特定类别,可以在URL中使用API​​端点的categoryID。 例如,下面的URL将让我搜索类别1(魔术聚集类别为1):

    #search the mtg catalog https://api.tcgplayer.com/catalog/categories/1/search

    While most API endpoints can be accessed with a GET request, some endpoints like Catalog > Search Category Products allow you to use a POST request to pass in filters to the request.

    虽然大多数API端点都可以通过GET请求进行访问,但是某些端点(例如Catalog> Search Category Products)允许您使用POST请求将过滤器传递给该请求。

    For example, say I want to search for the Magic: The Gathering card Tithe. I can pass a sort option, as well as filters and aggregations into the JSON payload.

    例如,假设我要搜索“魔术:聚会卡” 什一税。 我可以将排序选项以及过滤器和聚合传递到JSON有效负载中。

    url = "https://api.tcgplayer.com/catalog/categories/1/search"payload = {"sort":"Relevance", "filters": [{ "values": ["Tithe"], "name": "productName" }]}search_response = requests.request("POST", url, json=payload, headers=headers)search_response.json()

    The request returns a list of product IDs. Depending on how the items are sorted, the list of product IDs matches how the results display on TCGplayer.com

    该请求返回产品ID的列表。 根据项目的排序方式,产品ID列表与结果在TCGplayer.com上的显示方式匹配

    Search_response.text for Tithe sorted by Relevance Tithe的Search_response.text按相关性排序 Search Results for Tithe sorted by Relevance on TCGplayer.com 在TCGplayer.com上按相关程度对Tithe的搜索结果

    To retrieve the information about the cards in the search request, simply pass the comma separated list into the API endpoint URL.

    要在搜索请求中检索有关卡的信息,只需将逗号分隔的列表传递到API端点URL。

    endpoint = "https://api.tcgplayer.com/catalog/products/"productids = str(search_response.json()["results"])url = endpoint + productidsresponse = requests.get( url, headers=headers)response.json()

    Notice I simply combine the API endpoint with the list of product IDs.

    注意,我只是将API端点与产品ID列表结合在一起。

    response.json() response.json()

    Congratulations! You can now navigate and explore the TCGplayer API!

    恭喜你! 您现在可以浏览和探索TCGplayer API!

    最终思想和守则 (Final Thoughts and Code)

    Card games are not going anywhere and have matured into a popular niche. Magic: The Gathering has been around for nearly 30 years at this point! Using tools like the TCGplayer API, there is a unique opportunity for some data analysis and data science to take place and develop new tools and apps to help players build and manage their collections. Through the TCGplayer API, it is even possible to run your online store!

    纸牌游戏无处不在,已经发展成为一种流行的利基市场。 魔术:到现在为止聚会已经快30年了! 使用TCGplayer API这样的工具,就有机会进行一些数据分析和数据科学,并开发新的工具和应用程序来帮助玩家构建和管理自己的收藏。 通过TCGplayer API,甚至可以运行您的在线商店!

    If you enjoyed this article, check out my others on programming and data science:

    如果您喜欢这篇文章,请查看其他有关编程和数据科学的文章:

    完整的代码 (Complete Code)

    Below is the complete Code

    以下是完整的代码

    #import dependenciesimport requests#pull in api keys from config filefrom config import public_key, private_key#construct api requestresponse = requests.post( "https://api.tcgplayer.com/token",headers={ "Content-Type": "application/json", "Accept": "application/json"},data=(f"grant_type=client_credentials" f"&client_id={public_key}&" f"client_secret={private_key}") )access = response.json()['access_token']headers = {"accept": "application/json", "Content-Type": "application/json",'User-Agent': 'YOUR_USER_AGENT', "Authorization": "bearer " + access}url = "https://api.tcgplayer.com/catalog/categories"response = requests.get(url, headers=headers)print(response.json())url = "https://api.tcgplayer.com/catalog/categories/1/search"payload = {"sort":"Relevance", "filters": [{ "values": ["Tithe"], "name": "productName" }]}search_response = requests.request("POST", url, json=payload, headers=headers)print(search_response.json())endpoint = "https://api.tcgplayer.com/catalog/products/"productids = str(search_response.json()["results"])url = endpoint + productidsresponse = requests.get( url, headers=headers)response.json()

    翻译自: https://towardsdatascience.com/building-a-cardboard-empire-introduction-to-the-tcgplayer-api-using-python-fbfc2d62ef51

    python api介绍

    Processed: 0.012, SQL: 8