I'm trying to develop a code for uploading products on a marketplace site, but I'm encountering an error that I can't understand. The working structure of the code is to get the product photo links, price, discounted price, shipping fee, variation (color, size, variation stock quantity), stock quantity information from the user and upload it to the store via API.
import requests
url = "https://api.shopier.com/v1/products"
payload = {
"media": [
{
"type": "image",
"url": input("URL: "),
"placement": 1
},
{
"type": "image",
"url": input("URL: "),
"placement": 2
},
{
"type": "image",
"url": input("URL: "),
"placement": 3
},
{
"type": "image",
"url": input("URL: "),
"placement": 4
}
],
"priceData": {
"price": int(input("FİYAT: ")),
"discount": True,
"discountedPrice": int(input("İNDİRİMLİ FİYAT: ")),
"shippingPrice": int(input("KARGO ÜCRETİ: ")),
"currency": "TRY"
},
"categories": [{"categoryId": "1"}],
"variants": [
{
"selectionId": [
{
"V2": input("RENK: "),
"V1": input("Beden: ")
}
],
"stockQuantity": 50
}
],
"options": [
{
"optionId": "1",
"optionTitle": "Hediye Paketi Olsun",
"optionPrice": "10"
}
],
"title": "product_name",
"description": "product_desc",
"type": "physical",
"stockQuantity": 200,
"shippingPayer": "buyerPays",
"singleOption": True,
"customListing": False,
"customNote": "product_notes",
"placementScore": 1,
"dispatchDuration": 2
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": "Bearer +token"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
The error I get is like this:
{"error":"invalid","message":"variants[0].selectionId[0] must be a string"}
I removed the variation values this time the same product was loaded multiple times in the store and this is something customers don't like. customers want to choose color size on a single product page
Related
I will write sample code below. The errors I get are as follows:
It loads only the first image link from the visual links in the columns, skips the other links and starts uploading the product information. my other question is 40 requests per minute that api supports, but when I run the code, it tries to load all the data. After 40 data, I get error code 429, ie request limit exceeded. Can you help to solve these 2 situations?
import requests
import pandas as pd
# Load data from Excel
data = pd.read_excel("product_data.xlsx")
print(data.dtypes)
# Loop through each row in the dataframe
for index, row in data.iterrows():
url = "https://api.shopier.com/v1/products"
media = []
if row["Görsel URL1"]:
media.append({
"type": "image",
"url": row["Görsel URL1"],
"placement": int(1)
})
if row["Görsel URL2"]:
media.append({
"type": "image",
"url": row["Görsel URL2"],
"placement": int(2)
})
if row["Görsel URL3"]:
media.append({
"type": "image",
"url": row["Görsel URL3"],
"placement": int(3)
})
if row["Görsel URL4"]:
media.append({
"type": "image",
"url": row["Görsel URL4"],
"placement": int(4)
})
if row["Görsel URL5"]:
media.append({
"type": "image",
"url": row["Görsel URL5"],
"placement": int(5)
})
if row["Görsel URL6"]:
media.append({
"type": "image",
"url": row["Görsel URL6"],
"placement": int(6)
})
if row["Görsel URL7"]:
media.append({
"type": "image",
"url": row["Görsel URL7"],
"placement": int(7)
})
if row["Görsel URL8"]:
media.append({
"type": "image",
"url": row["Görsel URL8"],
"placement": int(8)
})
payload = {
"media": media,
"priceData": {
"currency": row["Para Birimi"],
"price": row["Fiyat"],
"discount": True,
"discountedPrice": row["İndirimli Fiyat"],
"shippingPrice": row["Kargo Ücreti"],
},
"options": [
{
"optionId": "1",
"optionTitle": "Hediye Paketi İstiyorum",
"optionPrice": "10"
}
],
"title": row["Ürün Başlığı"],
"description": row["Ürün Açıklaması"],
"type": "physical",
"stockQuantity": row["Stok Miktarı"],
"singleOption": True,
"customListing": False,
"customNote": "Sipariş ile ilgili detaylarınızı yazabilirsiniz.",
"shippingPayer": "sellerPays",
"dispatchDuration": row["Kargoya Teslim Süresi"],
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": "Bearer +token"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code != 200:
print("Error:", response.status_code)
else:
print(response.text)
I need your opinion for solution
Can't solve problem with POST and PUT request in strapi.io. My Relation is 1 to many (a ticket can have 1 category, a category can have many tickets).
GET request looks like this:
{
"data": {
"id": 1,
"attributes": {
"first_name": "Alex",
"last_name": "Porter",
"phone": "+74955978965",
"company": "Test",
"entry_time": null,
"entered": false,
"email": "test#test.com",
"count_entry": 0,
"createdAt": "2022-05-06T10:21:22.753Z",
"updatedAt": "2022-05-20T11:43:57.707Z",
"publishedAt": "2022-05-06T10:21:23.680Z",
"photo": {
"data": null
},
"category": {
"data": {
"id": 1,
"attributes": {
"name": "Junior",
"createdAt": "2022-05-20T11:36:46.360Z",
"updatedAt": "2022-05-20T11:37:17.517Z",
"publishedAt": "2022-05-20T11:37:17.516Z"
}
}
}
}
},
"meta": {}
}
This is what my function looks like with a PUT request:
def edit_member(self, member_id, first_name, last_name, phone, category):
url = config.SERVER + f'api/members/{member_id}?populate=%2A'
payload = {
'data': {
"attributes": {
"first_name": first_name,
"last_name": last_name,
"phone": phone,
},
"category": {
"data": {
"attributes": {
"name": category
}
}
}
}
}
headers = {
'Authorization': f'Bearer {config.TOKEN}',
'Content-Type': 'application/json'
}
requests.request("PUT", url, headers=headers, json=payload)
As a result, the data appears on the strapi, but the relation is lost (remains empty). Tell me, please, where to look?
Thank you in advance.
I'm a beginner and I'm getting a 422 error when running a code to extract data from an API endpoint. I Googled the code and realized it's an (Unprocessable Entity) status code, but I'm not sure how to fix it.
The documentation for the API is right here: https://github.com/fedspendingtransparency/usaspending-api/blob/master/usaspending_api/api_contracts/contracts/v2/search/spending_by_award.md
Can anyone please let me know how to modify my code?
import requests
url = "https://api.usaspending.gov"
endpoint = "/api/v2/search/spending_by_award"
criteria = {
"filters": {
"award_type_codes": ["10"],
"agencies": [
{
"type": "awarding",
"tier": "toptier",
"name": "Social Security Administration"
},
{
"type": "awarding",
"tier": "subtier",
"name": "Social Security Administration"
}
],
"legal_entities": [779928],
"recipient_scope": "domestic",
"recipient_locations": [650597],
"recipient_type_names": ["Individual"],
"place_of_performance_scope": "domestic",
"place_of_performance_locations": [60323],
"award_amounts": [
{
"lower_bound": 1500000.00,
"upper_bound": 1600000.00
}
],
"award_ids": [1018950]
},
"fields": ["Award ID", "Recipient Name", "Start Date", "End Date", "Award Amount", "Awarding Agency", "Awarding Sub Agency", "Award Type", "Funding Agency", "Funding Sub Agency"],
"sort": "Recipient Name",
"order": "desc"
}
response = requests.post(f"{url}{endpoint}", params=criteria)
print(response.status_code)
You may modify the data type of several fields, i.e., the award_ids should be a array[string], recipient_locations consists of array[LocationObject]
For a working example:
import requests
import json
url = "https://api.usaspending.gov/api/v2/search/spending_by_award"
payload = json.dumps({
"filters": {
"award_type_codes": [
"10"
],
"agencies": [
{
"type": "awarding",
"tier": "toptier",
"name": "Social Security Administration"
},
{
"type": "awarding",
"tier": "subtier",
"name": "Social Security Administration"
}
],
"legal_entities": [
779928
],
"recipient_scope": "domestic",
"recipient_type_names": [
"Individual"
],
"place_of_performance_scope": "domestic",
"award_amounts": [
{
"lower_bound": 1500000,
"upper_bound": 1600000
}
],
"award_ids": [
"1018950"
]
},
"fields": [
"Award ID",
"Recipient Name",
"Start Date",
"End Date",
"Award Amount",
"Awarding Agency",
"Awarding Sub Agency",
"Award Type",
"Funding Agency",
"Funding Sub Agency"
],
"sort": "Recipient Name",
"order": "desc"
})
headers = {
'Content-Type': 'application/json',
'Cookie': 'cookiesession1=678A3E0DCDEFGHIJKLNOPQRSTUV08936'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
print(response.status_code)
Result:
{
"limit": 10,
"results": [],
"page_metadata": {
"page": 1,
"hasNext": false,
"last_record_unique_id": null,
"last_record_sort_value": "None"
},
"messages": [
[
"For searches, time period start and end dates are currently limited to an earliest date of 2007-10-01. For data going back to 2000-10-01, use either the Custom Award Download feature on the website or one of our download or bulk_download API endpoints as listed on https://api.usaspending.gov/docs/endpoints."
]
]
}
I'm currently working with some JSON data that is presenting a challenge, i need to print the device name in my script next to the latency float, i can easily print the latency float as there is a key:value , however the device name does not sit the same, therefore i cannot figure out how to print this especially as it changes for each API Url i am looping through to retrieve the data
The data i want to print is "DEVICE123-Et10"
See JSON data below,
{
"notifications": [
{
"timestamp": "511513234234",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"httpResponseTime": {
"key": "httpResponseTime",
"value": {
"float": 0
}
}
}
},
{
"timestamp": "15153324243",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"packetLoss": {
"key": "packetLoss",
"value": {
"int": 0
}
}
}
},
{
"timestamp": "151522324234",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"latency": {
"key": "latency",
"value": {
"float": 0.238756565643454
}
}
}
},
{
"timestamp": "158056745645645",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"jitter": {
"key": "jitter",
"value": {
"float": 0.03500000213213
}
}
}
}
]
}
Current code i am using to loop through my URL list and get the latency:
jsonrequest = requests.get(url, cookies=cookies, verify=False).json()
try:
print(jsonrequest['notifications'][2]['updates']['latency']['value']['float'])
except KeyError:
print(jsonrequest['notifications'][1]['updates']['latency']['value']['float'])```
I went ahead and wrote a script to do what you wanted. It loops through all the notifications until a "latency" update is found. Then it takes the second-to-last item from the list, since it's always second to last.
import json
import requests
data = requests.get(url, cookies=cookies, verify=False).json()
notifications = data["notifications"]
for notification in notifications:
if notification["updates"].get("latency"):
latency = notification["updates"]["latency"]["value"]["float"]
name = notification["path_elements"][-2]
print(name, latency)
I have a response object that I am receiving from an api call. The response has several objects that are returned in a single call. What I want to do is grab information from each of the objects returned and store them in varialbes to use them within the application. I know to grab info from a json response when it returns a single objects but I am getting confused with multiples objects... I know how to automate the iteration process through something like a forloop... it wont iterate.
here is a sample response that I am getting:
I want to grab the _id from both items.
{
'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)",
'json':{
'_id':'..6e80',
'_links':{
'self':{
'href':'https://uat-api.synapsefi.com/v3.1/users/..22d/nodes/..56e80'
}
},
'allowed':'CREDIT-AND-DEBIT',
'client':{
'id':'..26a34',
'name':'Charlie Brown LLC'
},
'extra':{
'note':None,
'other':{
},
'supp_id':''
},
'info':{
'account_num':'8902',
'address':'PO BOX 85139, RICHMOND, VA, US',
'balance':{
'amount':'750.00',
'currency':'USD'
},
'bank_long_name':'CAPITAL ONE N.A.',
'bank_name':'CAPITAL ONE N.A.',
'class':'SAVINGS',
'match_info':{
'email_match':'not_found',
'name_match':'not_found',
'phonenumber_match':'not_found'
},
'name_on_account':' ',
'nickname':'SynapsePay Test Savings Account - 8902',
'routing_num':'6110',
'type':'BUSINESS'
},
<class 'synapse_pay_rest.models.nodes.ach_us_node.AchUsNode'>({
'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)",
'json':{
'_id':'..56e83',
'_links':{
'self':{
'href':'https://uat-api.synapsefi.com/v3.1/users/..d622d/nodes/..6e83'
}
},
'allowed':'CREDIT-AND-DEBIT',
'client':{
'id':'599378ec6aef1b0021026a34',
'name':'Charlie Brown LLC'
},
'extra':{
'note':None,
'other':{
},
'supp_id':''
},
'info':{
'account_num':'8901',
'address':'PO BOX 85139, RICHMOND, VA, US',
'balance':{
'amount':'800.00',
'currency':'USD'
},
'bank_long_name':'CAPITAL ONE N.A.',
'bank_name':'CAPITAL ONE N.A.',
'class':'CHECKING',
'match_info':{
'email_match':'not_found',
'name_match':'not_found',
'phonenumber_match':'not_found'
},
'name_on_account':' ',
'nickname':'SynapsePay Test Checking Account - 8901',
'routing_num':'6110',
'type':'BUSINESS'
},
})
Here is the code that I have:
It wont grab any values...
the iteration needs to be done to the nodes variable which is hte json response object.
def listedLinkAccounts(request):
currentUser = loggedInUser(request)
currentProfile = Profile.objects.get(user = currentUser)
user_id = currentProfile.synapse_id
synapseUser = SynapseUser.by_id(client, str(user_id))
options = {
'page':1,
'per_page':20,
'type': 'ACH-US',
}
nodes = Node.all(synapseUser, **options)
print(nodes)
response = nodes
_id = response["_id"]
print(_id)
return nodes
here is a sample api response from the api documenation:
{
"error_code": "0",
"http_code": "200",
"limit": 20,
"node_count": 5,
"nodes": [
{
"_id": "594e5c694d1d62002f17e3dc",
"_links": {
"self": {
"href": "https://uat-api.synapsefi.com/v3.1/users/594e0fa2838454002ea317a0/nodes/594e5c694d1d62002f17e3dc"
}
},
"allowed": "CREDIT-AND-DEBIT",
"client": {
"id": "589acd9ecb3cd400fa75ac06",
"name": "SynapseFI"
},
"extra": {
"other": {},
"supp_id": "ABC124"
},
"info": {
"account_num": "7443",
"address": "PLACE DE LA REPUBLIQUE 4 CROIX 59170 FR",
"balance": {
"amount": "0.00",
"currency": "USD"
},
"bank_long_name": "3 SUISSES INTERNATIONAL",
"bank_name": "3 SUISSES INTERNATIONAL",
"name_on_account": " ",
"nickname": "Some Account"
},
"is_active": true,
"timeline": [
{
"date": 1498307689471,
"note": "Node created."
},
{
"date": 1498307690130,
"note": "Unable to send micro deposits as node type is not ACH-US."
}
],
"type": "WIRE-INT",
"user_id": "594e0fa2838454002ea317a0"
},
{
...
},
{
...
},
...
],
"page": 1,
"page_count": 1,
"success": true
}