Webは用いる人のリテラシーで決まる ウェブ運用と開発現場を経験したエンジニアのTIPS
TOP > BLOG > IT記事

楽天の在庫API(InventoryAPI)を使ってPythonで在庫更新してみた

早川朋孝 早川朋孝
EC専門のSE

前回の記事楽天の在庫API(InventoryAPI)にPythonで在庫情報を取得してみたでは、指定の商品の在庫情報を単に取得しただけだった。

今回は手元の在庫情報を楽天の在庫に反映してみる。複数のモールに出店していて、マスターの在庫があり、それを楽天の在庫に反映するというような場面を想定するといいだろう。

在庫はsoapなのでちょい面倒くさいのだが、SKU移行後のinventory2.0でもsoap認証のようなので、新しい仕様でも面倒くさいのは変わらないと思われる。SKU移行後についてはまだ確認したわけではないので、確認ができ次第記事にする予定だ。楽天SKU対応のInventory2.0の記事はこちら

下記サンプルコードでは在庫数を50に設定し(inventory)、在庫タイプは通常在庫である2を(inventoryType)を設定した。在庫APIでは400個まで同時にリクエストできるらしい。

import zeep, base64
import requests
import time
import urllib.request
import urllib.error
import defusedxml.ElementTree as ET
import datetime

#楽天api
serviceSecret = 'hogehoge'
licenskey = 'hogehoge'
b64 = serviceSecret + ':' + licenskey
b64_en = base64.b64encode(b64.encode())
api_key = b'ESA ' + b64_en
api_key_str = str(api_key)
api_key_str = api_key_str[2:]
api_key_str = '' + api_key_str[:-1] + ''

url = 'https://api.rms.rakuten.co.jp/es/1.0/inventory/ws'

# 設定値
requestURL = url 
headers = {'Content-Type': 'text/xml;charset=UTF-8'}
method = 'POST'
shop_url = 'hogehoge'


def put_item_stock(shop_url, item_id):
    body = """<?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
     xmlns:ns1="java:jp.co.rakuten.rms.mall.inventoryapi.v1.model.entity"
     xmlns:ns2="https://inventoryapi.rms.rakuten.co.jp/rms/mall/inventoryapi"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="java:language_builtins.lang">
    <SOAP-ENV:Body>
    <ns2:updateInventoryExternal>
    <ns2:externalUserAuthModel>"""
    body += api_key_str
    body += """ 
    <ns1:userName>?</ns1:userName>
    <ns1:shopUrl>"""
    body += shop_url
    body +="""</ns1:shopUrl>
    </ns2:externalUserAuthModel>
    <ns2:updateRequestExternalModel>
     <ns1:updateRequestExternalItem>
      <ns1:UpdateRequestExternalItem>
       <ns1:inventory>50</ns1:inventory>
       <ns1:inventoryType>2</ns1:inventoryType>
       <ns1:itemUrl>"""
    body += item_id
    body += """</ns1:itemUrl>
       <ns1:inventoryUpdateMode>1</ns1:inventoryUpdateMode>
    </ns1:UpdateRequestExternalItem>
    </ns1:updateRequestExternalItem>
    </ns2:updateRequestExternalModel>
    </ns2:updateInventoryExternal>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>"""

    response = requests.post(url, data=body, headers=headers)
    xml_data = response.content.decode('utf-8')
    return xml_data
    
if __name__=="__main__":    
    item_id = 'hogehoge'
    put_item_stock(shop_url, item_id)
×
このブログを書いてる人
早川 朋孝 EC専門のSE
IT業界歴20年のエンジニアです。ネットショップ勤務で苦労した経験から、EC・ネットショップ事業者に向けて、バックオフィス業務の自動化・効率化を提案するSEをしています。
プロフィール
API連携の相談にのります
趣味は読書、ピアノ、マリノスの応援など
PAGE TOP