Python wrapper to access the amazon selling partner API

Overview

PYTHON-AMAZON-SP-API

CodeQL Tests

Maintainability Tech Coverage

Amazon Selling-Partner API

If you have questions, please join on slack

slack

Contributions very welcome!


Installation

Badge

pip install python-amazon-sp-api

Usage

# orders API
try:
    res = Orders().get_orders(CreatedAfter=(datetime.utcnow() - timedelta(days=7)).isoformat())
    print(res.payload)  # json data
except SellingApiException as ex:
    print(ex)


# report request     
createReportResponse = Reports().create_report(reportType='GET_FLAT_FILE_OPEN_LISTINGS_DATA')

# submit feed
# feeds can be submitted like explained in Amazon's docs, or simply by calling submit_feed

Feeds().submit_feed(self, <feed_type>, <file_or_bytes_io>, content_type='text/tsv', **kwargs)

Documentation

Documentation is available here

Documentation Status

DISCLAIMER

We are not affiliated with Amazon

LICENSE

License

Comments
  • 'message': 'Access to requested resource is denied.',    'code': 'Unauthorized' issue

    'message': 'Access to requested resource is denied.', 'code': 'Unauthorized' issue

    I have been getting this error for every request. I currently have a Seller Central account and I am trying to gain access to the api. I have followed the documentation provided by amazon to set up the necessary credentials, but still receive the 'Access to requested resource is denied.' error message. I have checked in on the access_token that is being generated and it matches the 'Atza|xxxxxx' format, so I do not believe that is the issue.

    Additionally, I have been following the Self Authorization guidelines to get the refresh token used here, so I am unsure as to why I am getting the error.

    I have searched through the issues here and under the Seller-partner-api-docs and found no solution.

    from sp_api.api.orders.orders import Orders
    
    os.environ["SP_API_REFRESH_TOKEN"] = "Atzr|xxxxxxxx"
    os.environ["LWA_APP_ID"] = "amzn1.application-oa2-client.xxxxxxxx"
    os.environ["LWA_CLIENT_SECRET"] = "xxxxxxxx"
    os.environ["SP_API_SECRET_KEY"] = "xxxxxxxx"
    os.environ["SP_API_ACCESS_KEY"] = "xxxxxxxx"
    os.environ["SP_API_ROLE_ARN"] = "arn:aws:iam::xxxxxxxx:role/SellerPartnerAPIRole"
    os.environ["SP_AWS_REGION"] = "us-east-1"
    
    try:
        res = Orders().get_orders(CreatedAfter=(datetime.datetime.utcnow() - datetime.timedelta(days=7)).isoformat())
        print(res.payload)  # json data
    except SellingApiException as ex:
        print(ex)
    

    output {'Date': 'Wed, 27 Jan 2021 15:22:51 GMT', 'Content-Type': 'application/json', 'Content-Length': '141', 'Connection': 'keep-alive', 'x-amzn-RequestId': '387bf5b0-58c6-4dee-93a0-47c3da1fadc0', 'x-amzn-ErrorType': 'AccessDeniedException', 'x-amz-apigw-id': 'Z0HDvHjOoAMF0Aw='} {'errors': [{'message': 'Access to requested resource is denied.', 'code': 'Unauthorized', 'details': ''}]} [{'message': 'Access to requested resource is denied.', 'code': 'Unauthorized', 'details': ''}]

    Any help will be greatly appreciated!

    opened by The-Geology-Guy 34
  • Request headers are not editable, causing problem with RDT

    Request headers are not editable, causing problem with RDT

    Orders

    To get more information about ShippingAddress and BuyerInfo from getOrders calls we have to pass restricted data token to request headers. Instead of using access token for x-amz-access-token, we need to pass RDT.

    As far as I see there is no way to reach request headers to edit it.

    My Suggestion

    response = Orders(**credentials).get_orders(**params, restricted_data_token="Atz.r|...")

    Restricted data token is special for order endpoints. So I believe we can implement a usage like above.

    I can work on it and open a pull request next 1 or 2 days.

    What do you think?

    enhancement hacktoberfest 
    opened by ethemguner 15
  • Getting error from sample code. Need clear documentation to run that at least.

    Getting error from sample code. Need clear documentation to run that at least.

    Describe the bug When I run the sample code in the readme.md, it doesn't succeed.

    To Reproduce Steps to reproduce the behavior:

    1. Go to '...'
    2. Click on '....'
    3. Scroll down to '....'
    4. See error

    Expected behavior A clear and concise description of what you expected to happen.

    Desktop (please complete the following information):

    • OS: Ubuntu 20
    • Browser:
    • Version [e.g. 22]

    Smartphone (please complete the following information):

    • Device: [e.g. iPhone6]
    • OS: [e.g. iOS8.1]
    • Browser [e.g. stock browser, safari]
    • Version [e.g. 22]

    Additional context Add any other context about the problem here.

    question 
    opened by fkhjoy 14
  • Force user SKU quote

    Force user SKU quote

    ProductFees() api does not encript SKU containing forward slash as described here #431

    As SKU is part of URL some of the chars in SKU could yield issue with URL formatting so we get SellingApiForbiddenException due invalid URL

    Fix should handle this behavior.
    Also there is option to disable this conversion if needed as I imagine there will be cases where this will be problematic.

    Currently it will default to True so all SKU will be quoted.

    opened by abrihter 12
  • UnicodeEncodeError when downloading/decrypting using Reports().get_report_document()

    UnicodeEncodeError when downloading/decrypting using Reports().get_report_document()

    Describe the bug Python throws a UnicodeEncodeError exception when using Reports().get_report_document().

    To Reproduce Steps to reproduce the behavior:

    # report request
    createReportResponse = Reports(credentials=credentials
        ,marketplace=marketplaces.Marketplaces.CA).create_report(
            reportType="GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT",
            reportOptions={"reportPeriod": "WEEK"},
            dataStartTime="2021-10-03",
            dataEndTime="2021-10-09"
            )
    
    # report id
    report_id = createReportResponse.payload['reportId']
    print("Report ID: ", report_id)
    
    # get report (loop)
    getReportResponse = Reports(credentials=credentials, marketplace=marketplaces.Marketplaces.CA).get_report(report_id=report_id)
    while getReportResponse.payload['processingStatus'] != 'DONE':
        print("Report status is: %s. Sleeping for 10 seconds..." % getReportResponse.payload['processingStatus'])
        time.sleep(10)
        getReportResponse = Reports(credentials=credentials, marketplace=marketplaces.Marketplaces.CA).get_report(report_id=report_id)
    
    # report document id
    report_document_id = getReportResponse.payload['reportDocumentId']
    print("Report document ID: ", report_document_id)
    
    # create filename
    output_file = report_document_id + ".json"
    
    # get report document
    getReportDocumentResponse = Reports(credentials=credentials,
        marketplace=marketplaces.Marketplaces.CA).get_report_document(
            document_id=report_document_id,
            decrypt=True,
            file=output_file,
            character_code='utf-8'
            )
    

    Expected behavior Report download, decrypts, and decompresses without throwing an exception.

    Desktop (please complete the following information):

    • OS: Windows 10

    Additional context I've tried specifying different values for character_code such as iso-8859-1 but I still get an exception.

    bug 
    opened by Guerri114 11
  • Problem with request

    Problem with request

    Hi, we have communication problem with amazon. Our client logs in to our service where he clicks button "Log in Amazon". He is then redirected to url https://sellercentral.amazon.pl/apps/authorize/consent?application_id=amzn1.sellerapps.app.xxxx-xxxx-xxx-xxx-xxx&state=here_is_unique_uid. On this page our partner accepts the usage for our application and is redirected back, from that action we get selling_partner_id and spapi_oauth_code. After that we send request on https://api.amazon.com/auth/o2/token with data: {'grant_type': "authorization_code", 'code': spapi_oauth_code, 'redirect_uri': redirect_url, 'client_id': AMAZON_CLIENT_ID,
    'client_secret': AMAZON_SECRET } where AMAZON_CLIENT_ID and AMAZON_SECRET are LWA credentials of app. In response we receive access_token and refresh token. Till this point everything works fine.

    Now we try to get orders data: 1. We request Login with Amazon access token on /auth/o2/token with params: client_id, client_secret (LWA credentials of app) grant_type=refresh_token, refresh_token=refresh token we have from previous step. In response we receive new access_token and refresh_token.

    We create assume role request on sts.amazonaws.com using AWS_ACCESS from AWS for credential and AWS_SECRET from AWS for computing signature. From that response we get SessionToken and accesskeyid.

    Final request for orders: GET on sellingpartnerapi-eu.amazon.com/orders/v0/orders in Authorization header for credential we use accesskeyid from assume role request, for X-Amz-Access-Token header we use access token from 1st request, and for X-Amz-Security-Token we send sessiontoken received from assumrole request for that data we receive 403 forbidden error HTTP/2.0 403 Forbidden Content-Length: 141 Content-Type: application/json Date: Wed, 07 Apr 2021 13:33:57 GMT X-Amz-Apigw-Id: daku6GYXDoEFQPw= X-Amzn-Errortype: AccessDeniedException X-Amzn-Requestid: 55ff0680-a7c1-412d-830d-cc3b018ea1b9

    { "errors": [ { "message": "Access to requested resource is denied.", "code": "Unauthorized", "details": "" } ] }

    We don't have idea what is wrong. Our app have a access permission to get order.

    bug 
    opened by sw69 11
  • getListingsItem doesn't work if there are white spaces in SKU Param

    getListingsItem doesn't work if there are white spaces in SKU Param

    When calling ListingItems.get_listing_item() passing in a SKU that contains whitespaces results in a NOT FOUND error. It seems like the whitespaces are being encoded/ encoded improperly? Can't fully tell what is causing the issue but it is returning

    [{'code': 'NOT_FOUND', 'message': "SKU 'XXXX%20YYY%20ZZZ' not found in marketplace ATVPDKIKX0DER"}]

    bug 
    opened by DanielLanger 9
  • AttributeError: 'list' object has no attribute 'get'

    AttributeError: 'list' object has no attribute 'get'

    I am calling the get_order endpoint like this, api_response = orders_api.get_orders( CreatedAfter=created_after, CreatedBefore=created_before, NextToken=next_token, ) and it was working very well recently, but now when I call it, I get this error File "/mnt/c/Users/ayubz/Documents/Amazing Brand/amazon-due-diligence/logic/get_orders.py", line 49, in get_orders api_response = orders_api.get_orders( File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/base/helpers.py", line 21, in wrapper return function(*args, **kwargs) File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/api/orders/orders.py", line 51, in get_orders return self._request(kwargs.pop('path'), params={**kwargs}) File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/base/client.py", line 114, in _request return self._check_response(res) File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/base/client.py", line 118, in _check_response error = res.json().get('errors', None) AttributeError: 'list' object has no attribute 'get' Any idea why this might be happening?

    bug 
    opened by Zakir-Ayub 9
  • restrictedResources only works if not is an array

    restrictedResources only works if not is an array

    Describe the bug When I call create_restricted_data_token only works when restrictedResources is called like and object, not as array.

    To Reproduce

    This not works: token_res = Tokens().create_restricted_data_token(restrictedResources=[{ "method": "GET", "path": "/orders/v0/orders", "dataElements": ["buyerInfo", "shippingAddress"] } ])

    This works: token_res = Tokens().create_restricted_data_token(restrictedResources={ "method": "GET", "path": "/orders/v0/orders", "dataElements": ["buyerInfo", "shippingAddress"] } )

    I don't know if it is a documentation mistake o a bug in the api.

    bug 
    opened by ximo1984 9
  • def get_product_fees_estimate(self, estimate_requests: list[dict]) -> ApiResponse:

    def get_product_fees_estimate(self, estimate_requests: list[dict]) -> ApiResponse:

    I'm testing it for the first time today. I am getting this error even though I have everything set up correctly.

    What is the reason for this error?

    File "D:\anaconda3\lib\site-packages\sp_api\api\product_fees\product_fees.py", line 99, in ProductFees def get_product_fees_estimate(self, estimate_requests: list[dict]) -> ApiResponse: TypeError: 'type' object is not subscriptable

    from sp_api.base import Marketplaces
    from sp_api.api import Orders
    
    credentials = dict(
        refresh_token='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From Seller central under Authorise -> Refresh Token
        lwa_app_id='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From Seller Central, named CLIENT IDENTIFIER on website.
        lwa_client_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From Seller Central, named CLIENT SECRET on website.
        aws_access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From AWS IAM Setup
        aws_secret_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From AWS IAM Setup
        role_arn='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  #arn:aws:iam::1234567890:role/SellingPartnerAPIRole
    )
    
    order_client = Orders(credentials=credentials, marketplace=Marketplaces.AU)
    order = order_client.get_order('111-4412524-0850212')
    print(order) # `order` is an `ApiResponse`
    print(order.payload) # `payload` contains the original response
    

    Thank you

    bug 
    opened by cnr91 8
  • Inventory API not working...

    Inventory API not working...

    I'm requesting by following code. inventoryClient = api.Inventories(credentials=self.credentials, marketplace=Marketplaces.JP) res = inventoryClient.get_inventory_summary_marketplace(sellerSkus=['sku1', 'sku2']) Then I'm getting error.

    sp_api.base.exceptions.SellingApiForbiddenException: [{'message': 'Access to requested resource is denied.', 'code': 'Unauthorized', 'details': ''}]

    However my credentials is correct. Other API(feed, report...) is working. Please help me.

    opened by kstar0101 8
Releases(v0.17.5)
Inflated i3d network with inception backbone, weights transfered from tensorflow

I3D models transfered from Tensorflow to PyTorch This repo contains several scripts that allow to transfer the weights from the tensorflow implementat

Yana 479 Dec 08, 2022
HSC4D: Human-centered 4D Scene Capture in Large-scale Indoor-outdoor Space Using Wearable IMUs and LiDAR. CVPR 2022

HSC4D: Human-centered 4D Scene Capture in Large-scale Indoor-outdoor Space Using Wearable IMUs and LiDAR. CVPR 2022 [Project page | Video] Getting sta

51 Nov 29, 2022
Capsule endoscopy detection DACON challenge

capsule_endoscopy_detection (DACON Challenge) Overview Yolov5, Yolor, mmdetection기반의 모델을 사용 (총 11개 모델 앙상블) 모든 모델은 학습 시 Pretrained Weight을 yolov5, yolo

MAILAB 11 Nov 25, 2022
How to Leverage Multimodal EHR Data for Better Medical Predictions?

How to Leverage Multimodal EHR Data for Better Medical Predictions? This repository contains the code of the paper: How to Leverage Multimodal EHR Dat

13 Dec 13, 2022
Official Codes for Graph Modularity:Towards Understanding the Cross-Layer Transition of Feature Representations in Deep Neural Networks.

Dynamic-Graphs-Construction Official Codes for Graph Modularity:Towards Understanding the Cross-Layer Transition of Feature Representations in Deep Ne

11 Dec 14, 2022
Official code repository of the paper Learning Associative Inference Using Fast Weight Memory by Schlag et al.

Learning Associative Inference Using Fast Weight Memory This repository contains the offical code for the paper Learning Associative Inference Using F

Imanol Schlag 18 Oct 12, 2022
Posterior temperature optimized Bayesian models for inverse problems in medical imaging

Posterior temperature optimized Bayesian models for inverse problems in medical imaging Max-Heinrich Laves*, Malte Tölle*, Alexander Schlaefer, Sandy

Artificial Intelligence in Cardiovascular Medicine (AICM) 6 Sep 19, 2022
ContourletNet: A Generalized Rain Removal Architecture Using Multi-Direction Hierarchical Representation

ContourletNet: A Generalized Rain Removal Architecture Using Multi-Direction Hierarchical Representation (Accepted by BMVC'21) Abstract: Images acquir

10 Dec 08, 2022
TargetAllDomainObjects - A python wrapper to run a command on against all users/computers/DCs of a Windows Domain

TargetAllDomainObjects A python wrapper to run a command on against all users/co

Podalirius 19 Dec 13, 2022
Pipeline for employing a Lightweight deep learning models for LOW-power systems

PL-LOW A high-performance deep learning model lightweight pipeline that gradually lightens deep neural networks in order to utilize high-performance d

POSTECH Data Intelligence Lab 9 Aug 13, 2022
MOOSE (Multi-organ objective segmentation) a data-centric AI solution that generates multilabel organ segmentations to facilitate systemic TB whole-person research

MOOSE (Multi-organ objective segmentation) a data-centric AI solution that generates multilabel organ segmentations to facilitate systemic TB whole-person research.The pipeline is based on nn-UNet an

QIMP team 30 Jan 01, 2023
AdelaiDet is an open source toolbox for multiple instance-level detection and recognition tasks.

AdelaiDet is an open source toolbox for multiple instance-level detection and recognition tasks.

Adelaide Intelligent Machines (AIM) Group 3k Jan 02, 2023
A python program to hack instagram

hackinsta a program to hack instagram Yokoback_(instahack) is the file to open, you need libraries write on import. You run that file in the same fold

2 Jan 22, 2022
Pytorch code for paper "Image Compressed Sensing Using Non-local Neural Network" TMM 2021.

NL-CSNet-Pytorch Pytorch code for paper "Image Compressed Sensing Using Non-local Neural Network" TMM 2021. Note: this repo only shows the strategy of

WenxueCui 7 Nov 07, 2022
This Jupyter notebook shows one way to implement a simple first-order low-pass filter on sampled data in discrete time.

How to Implement a First-Order Low-Pass Filter in Discrete Time We often teach or learn about filters in continuous time, but then need to implement t

Joshua Marshall 4 Aug 24, 2022
Pytorch implementation of the AAAI 2022 paper "Cross-Domain Empirical Risk Minimization for Unbiased Long-tailed Classification"

[AAAI22] Cross-Domain Empirical Risk Minimization for Unbiased Long-tailed Classification We point out the overlooked unbiasedness in long-tailed clas

PatatiPatata 28 Oct 18, 2022
Official PyTorch implementation of MAAD: A Model and Dataset for Attended Awareness

MAAD: A Model for Attended Awareness in Driving Install // Datasets // Training // Experiments // Analysis // License Official PyTorch implementation

7 Oct 16, 2022
WSDM‘2022: Knowledge Enhanced Sports Game Summarization

Knowledge Enhanced Sports Game Summarization Cooming Soon! :) Data will be released after approval process. Code will be published once the author of

Jiaan Wang 14 Jul 13, 2022
Rank 1st in the public leaderboard of ScanRefer (2021-03-18)

InstanceRefer InstanceRefer: Cooperative Holistic Understanding for Visual Grounding on Point Clouds through Instance Multi-level Contextual Referring

63 Dec 07, 2022
This is the code for the paper "Motion-Focused Contrastive Learning of Video Representations" (ICCV'21).

Motion-Focused Contrastive Learning of Video Representations Introduction This is the code for the paper "Motion-Focused Contrastive Learning of Video

11 Sep 23, 2022