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)
Red Team tool for exfiltrating files from a target's Google Drive that you have access to, via Google's API.

GD-Thief Red Team tool for exfiltrating files from a target's Google Drive that you(the attacker) has access to, via the Google Drive API. This includ

Antonio Piazza 39 Dec 27, 2022
Amazon Forest Computer Vision: Satellite Image tagging code using PyTorch / Keras with lots of PyTorch tricks

Amazon Forest Computer Vision Satellite Image tagging code using PyTorch / Keras Here is a sample of images we had to work with Source: https://www.ka

Mamy Ratsimbazafy 360 Dec 10, 2022
Abstractive opinion summarization system (SelSum) and the largest dataset of Amazon product summaries (AmaSum). EMNLP 2021 conference paper.

Learning Opinion Summarizers by Selecting Informative Reviews This repository contains the codebase and the dataset for the corresponding EMNLP 2021

Arthur Bražinskas 39 Jan 1, 2023
Amazon Forest Computer Vision: Satellite Image tagging code using PyTorch / Keras with lots of PyTorch tricks

Amazon Forest Computer Vision Satellite Image tagging code using PyTorch / Keras Here is a sample of images we had to work with Source: https://www.ka

Mamy Ratsimbazafy 359 Jan 5, 2023
A voice recognition assistant similar to amazon alexa, siri and google assistant.

kenyan-Siri Build an Artificial Assistant Full tutorial (video) To watch the tutorial, click on the image below Installation For windows users (run th

Alison Parker 3 Aug 19, 2022
A project to make Amazon Echo respond to sign language using your webcam

Making Alexa respond to Sign Language using Tensorflow.js Try the live demo Read the Blog Post on Tensorflow's Blog Coming Soon Watch the video This p

Abhishek Singh 444 Jan 3, 2023
Build an Amazon SageMaker Pipeline to Transform Raw Texts to A Knowledge Graph

Build an Amazon SageMaker Pipeline to Transform Raw Texts to A Knowledge Graph This repository provides a pipeline to create a knowledge graph from ra

AWS Samples 3 Jan 1, 2022
AWS provides a Python SDK, "Boto3" ,which can be used to access the AWS-account from the local.

Boto3 - The AWS SDK for Python Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python, which allows Python developers to wri

Shreyas Srivastava 1 Oct 25, 2021
A series of Python scripts to access measurements from Fluke 28X meters. Fluke IR Remote Interface required.

Fluke289_data_access A series of Python scripts to access measurements from Fluke 28X meters. Fluke IR Remote Interface required. Created from informa

null 3 Dec 8, 2022
Framework for abstracting Amiga debuggers and access to AmigaOS libraries and devices.

Framework for abstracting Amiga debuggers. This project provides abstration to control an Amiga remotely using a debugger. The APIs are not yet stable

Roc Vallès 39 Nov 22, 2022
This repo contains the code and data used in the paper "Wizard of Search Engine: Access to Information Through Conversations with Search Engines"

Wizard of Search Engine: Access to Information Through Conversations with Search Engines by Pengjie Ren, Zhongkun Liu, Xiaomeng Song, Hongtao Tian, Zh

null 19 Oct 27, 2022
Rayvens makes it possible for data scientists to access hundreds of data services within Ray with little effort.

Rayvens augments Ray with events. With Rayvens, Ray applications can subscribe to event streams, process and produce events. Rayvens leverages Apache

CodeFlare 32 Dec 25, 2022
An open-access benchmark and toolbox for electricity price forecasting

epftoolbox The epftoolbox is the first open-access library for driving research in electricity price forecasting. Its main goal is to make available a

null 97 Dec 5, 2022
Differentiable Neural Computers, Sparse Access Memory and Sparse Differentiable Neural Computers, for Pytorch

Differentiable Neural Computers and family, for Pytorch Includes: Differentiable Neural Computers (DNC) Sparse Access Memory (SAM) Sparse Differentiab

ixaxaar 302 Dec 14, 2022
Multiple types of NN model optimization environments. It is possible to directly access the host PC GUI and the camera to verify the operation. Intel iHD GPU (iGPU) support. NVIDIA GPU (dGPU) support.

mtomo Multiple types of NN model optimization environments. It is possible to directly access the host PC GUI and the camera to verify the operation.

Katsuya Hyodo 24 Mar 2, 2022
ViViT: Curvature access through the generalized Gauss-Newton's low-rank structure

ViViT is a collection of numerical tricks to efficiently access curvature from the generalized Gauss-Newton (GGN) matrix based on its low-rank structure. Provided functionality includes computing

Felix Dangel 12 Dec 8, 2022
StocksMA is a package to facilitate access to financial and economic data of Moroccan stocks.

Creating easier access to the Moroccan stock market data What is StocksMA ? StocksMA is a package to facilitate access to financial and economic data

Salah Eddine LABIAD 28 Jan 4, 2023
A simple API wrapper for Discord interactions.

Your ultimate Discord interactions library for discord.py. About | Installation | Examples | Discord | PyPI About What is discord-py-interactions? dis

james 641 Jan 3, 2023