Skip to content

Commit

Permalink
added all endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
saleweaver committed May 21, 2021
1 parent 903fbae commit 04c1a3e
Show file tree
Hide file tree
Showing 41 changed files with 2,755 additions and 2 deletions.
Empty file added make_endpoint/__init__.py
Empty file.
157 changes: 157 additions & 0 deletions make_endpoint/make_endpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import json
import os
import pprint
import re
import sys

import jinja2
import requests


def get_model(url):
res = requests.get(url).json()
return res


def make_query(p):
r = r'{.*}'
try:
return re.sub(r, '{}', p), p[p.index('{') + 1:p.index('}')], True
except ValueError:
return re.sub(r, '{}', p), None, False


def make_py(endpoint, operations, description, directory):
context = {
'endpoint': endpoint,
'operations': operations,
'description': description
}
loader = jinja2.FileSystemLoader(searchpath="./")
env = jinja2.Environment(loader=loader)
file = "template.py.jinja2"
template = env.get_template(file)
out = template.render(context)

with open(os.path.join(directory, f'{sub(endpoint)}.py'), 'w+') as f:
f.write(out)
f.close()


def sub(e):
return re.sub(r'([A-Z])', lambda match: r'_{}'.format(match.group(1).lower()), e[0].lower() + e[1:])


def make_endpoint_name(s):
return re.sub(r'-([a-zA-Z])', lambda match: r'{}'.format(match.group(1).upper()), s[0].upper() + s[1:])


def make_directory(endpoint):
directory = f'../sp_api/api/{sub(endpoint)}'
if os.path.exists(directory):
raise Exception('Directory exists')
os.mkdir(directory)
open(os.path.join(directory, '__init__.py'), 'a').close()
return directory


def make_params(params, model):
if not params:
return []
new_params = []
for param in params:
if param.get('in') == 'body':
body = model.get('definitions').get(param.get('schema').get('$ref')[param.get('schema').get('$ref').rindex('/') + 1:])
body_example = pprint.pformat(body, width=250, compact=False)
param.update({'description': body_example})
new_params.append(param)
return new_params


def add_to_init(endpoint):
e = sub(endpoint)
import_template = f'''##### DO NOT DELETE ########## INSERT IMPORT HERE #######
from .{e}.{e} import {endpoint}
'''
append_template = f'''##### DO NOT DELETE ########## INSERT TITLE HERE #######
"{endpoint}",
'''
with open('../sp_api/api/__init__.py', 'r') as f:
content = f.read()
content = import_template.join(content.split('##### DO NOT DELETE ########## INSERT IMPORT HERE #######'))
content = append_template.join(content.split('##### DO NOT DELETE ########## INSERT TITLE HERE #######'))
f.close()
with open('../sp_api/api/__init__.py', 'w+') as f1:
f1.write(content)
f1.close()


def add_to_setup_py(endpoint):
package = f"'sp_api.api.{sub(endpoint)}'"
append_template = f"""##### DO NOT DELETE ########## INSERT PACKAGE HERE #######
{package},
"""
with open('../setup.py', 'r') as f:
content = f.read()
content = append_template.join(content.split('##### DO NOT DELETE ########## INSERT PACKAGE HERE #######'))
f.close()
with open('../setup.py', 'w+') as f1:
f1.write(content)
f1.close()


def create_endpoint_file(model_json):
model = get_model(model_json)
endpoint = get_endpoint_from_url(model_json)
operations = []
for k, v in model.get('paths').items():
for method, val in v.items():
if method == 'parameters':
continue
uri, param, has_query_params = make_query(k)
operation = {
'uri': uri,
'method': method.upper(),
'has_query_params': has_query_params,
'query_param': param,
'params_or_data': 'params' if method == 'get' else 'data',
'title': sub(val.get('operationId')),
'description': val.get('description'),
'params': make_params(val.get('parameters'), model)
}
operations.append(operation)

make_py(endpoint, operations, model.get('info').get('description'), make_directory(endpoint))
add_to_init(endpoint)
add_to_setup_py(endpoint)

def get_endpoint_from_url(url):
n = url.split('/')[-2][:-10]
return make_endpoint_name(n)


if __name__ == '__main__':
for model_json_url in [
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/fulfillment-outbound-api-model/fulfillmentOutbound_2020-07-01.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/aplus-content-api-model/aplusContent_2020-11-01.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/authorization-api-model/authorization.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/fba-inbound-eligibility-api-model/fbaInbound.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/fba-small-and-light-api-model/fbaSmallandLight.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/services-api-model/services.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/shipping-api-model/shipping.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/solicitations-api-model/solicitations.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/tokens-api-model/tokens_2021-03-01.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-direct-fulfillment-inventory-api-model/vendorDirectFulfillmentInventoryV1.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-direct-fulfillment-orders-api-model/vendorDirectFulfillmentOrdersV1.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-direct-fulfillment-payments-api-model/vendorDirectFulfillmentPaymentsV1.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-direct-fulfillment-shipping-api-model/vendorDirectFulfillmentShippingV1.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-direct-fulfillment-transactions-api-model/vendorDirectFulfillmentTransactionsV1.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-invoices-api-model/vendorInvoices.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-orders-api-model/vendorOrders.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-shipments-api-model/vendorShipments.json',
'https://raw.githubusercontent.com/amzn/selling-partner-api-models/main/models/vendor-transaction-status-api-model/vendorTransactionStatus.json'
]:
try:
create_endpoint_file(model_json_url)
except Exception as e:
print(e)
35 changes: 35 additions & 0 deletions make_endpoint/template.py.jinja2
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import urllib.parse

from sp_api.base import Client, sp_endpoint, fill_query_params, ApiResponse


class {{ endpoint }}(Client):
"""
{{ endpoint }} SP-API Client
:link: {{ docs_link }}

{{ description }}
"""

{% for operation in operations %}
@sp_endpoint('{{ operation.uri }}', method='{{ operation.method }}')
def {{ operation.title }}(self, {{ (operation.query_param + ', ') if operation.has_query_params }}**kwargs) -> ApiResponse:
"""
{{ operation.title }}(self, {{ (operation.query_param + ', ') if operation.has_query_params }}**kwargs) -> ApiResponse

{{ operation.description }}

Args:
{% for arg in operation.params %}
{{ 'key ' if arg['in'] == 'query' else ''}}{{ arg.name }}:{{ arg.type }} | {{ '* REQUIRED' if arg.required else '' }} {{ arg.description }}
{% endfor %}

Returns:
ApiResponse:
"""
{% if operation.has_query_params %}
return self._request(fill_query_params(kwargs.pop('path'), {{ operation.query_param }}), {{ operation.params_or_data }}=kwargs)
{% else %}
return self._request(kwargs.pop('path'), {{ operation.params_or_data }}=kwargs)
{% endif %}
{% endfor %}
41 changes: 40 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,46 @@
'sp_api.api.merchant_fulfillment',
'sp_api.api.fulfillment_inbound',
'sp_api.auth',
'sp_api.base'],
'sp_api.base',
##### DO NOT DELETE ########## INSERT PACKAGE HERE #######
'sp_api.api.vendor_transaction_status',

'sp_api.api.vendor_shipments',

'sp_api.api.vendor_orders',

'sp_api.api.vendor_invoices',

'sp_api.api.vendor_direct_fulfillment_transactions',

'sp_api.api.vendor_direct_fulfillment_shipping',

'sp_api.api.vendor_direct_fulfillment_payments',

'sp_api.api.vendor_direct_fulfillment_orders',

'sp_api.api.vendor_direct_fulfillment_inventory',

'sp_api.api.tokens',

'sp_api.api.solicitations',

'sp_api.api.shipping',

'sp_api.api.services',

'sp_api.api.fba_small_and_light',

'sp_api.api.fba_inbound_eligibility',

'sp_api.api.authorization',

'sp_api.api.aplus_content',

'sp_api.api.fulfillment_outbound',


],
url='https://github.com/saleweaver/python-amazon-sp-api',
license='MIT',
author='Michael',
Expand Down
79 changes: 78 additions & 1 deletion sp_api/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,45 @@
from .messaging.messaging import Messaging
from .merchant_fulfillment.merchant_fulfillment import MerchantFulfillment

##### DO NOT DELETE ########## INSERT IMPORT HERE #######
from .vendor_transaction_status.vendor_transaction_status import VendorTransactionStatus

from .vendor_shipments.vendor_shipments import VendorShipments

from .vendor_orders.vendor_orders import VendorOrders

from .vendor_invoices.vendor_invoices import VendorInvoices

from .vendor_direct_fulfillment_transactions.vendor_direct_fulfillment_transactions import VendorDirectFulfillmentTransactions

from .vendor_direct_fulfillment_shipping.vendor_direct_fulfillment_shipping import VendorDirectFulfillmentShipping

from .vendor_direct_fulfillment_payments.vendor_direct_fulfillment_payments import VendorDirectFulfillmentPayments

from .vendor_direct_fulfillment_orders.vendor_direct_fulfillment_orders import VendorDirectFulfillmentOrders

from .vendor_direct_fulfillment_inventory.vendor_direct_fulfillment_inventory import VendorDirectFulfillmentInventory

from .tokens.tokens import Tokens

from .solicitations.solicitations import Solicitations

from .shipping.shipping import Shipping

from .services.services import Services

from .fba_small_and_light.fba_small_and_light import FbaSmallAndLight

from .fba_inbound_eligibility.fba_inbound_eligibility import FbaInboundEligibility

from .authorization.authorization import Authorization

from .aplus_content.aplus_content import AplusContent

from .fulfillment_outbound.fulfillment_outbound import FulfillmentOutbound



__all__ = [
"Sales",
"Products",
Expand All @@ -30,5 +69,43 @@
'Upload',
"Messaging",
"FulfillmentInbound",
"MerchantFulfillment"
"MerchantFulfillment",
##### DO NOT DELETE ########## INSERT TITLE HERE #######
"VendorTransactionStatus",

"VendorShipments",

"VendorOrders",

"VendorInvoices",

"VendorDirectFulfillmentTransactions",

"VendorDirectFulfillmentShipping",

"VendorDirectFulfillmentPayments",

"VendorDirectFulfillmentOrders",

"VendorDirectFulfillmentInventory",

"Tokens",

"Solicitations",

"Shipping",

"Services",

"FbaSmallAndLight",

"FbaInboundEligibility",

"Authorization",

"AplusContent",

"FulfillmentOutbound",


]
Empty file.
Loading

0 comments on commit 04c1a3e

Please sign in to comment.