In Shopify, using REST API's or GraphQL, can I simultaneously open and work with two stores - rest

I need to duplicate some information between two stores ( one being the source store and the other the destination store ) .. can I open access to both stores, do a fetch data query on the source store and then mutate to the destination store, rather than having to use an intermediate storage file or memory, as the data size is large.

Yes, you can. In the most simple case you need a private app for each of the two stores. Then your calls to the REST or GraphQL API are constructed in such a way that they address the respectiv store. In Python this might look like the follwing
import base64
import requests
API_VERSION = '2022-01'
API_KEY1 = "API_KEY for private app of store 1")
PASSWORD1 = "PASSWORD for private app of store 1")
CREDENTIAL1 = f'{API_KEY1}:{PASSWORD1}'
auth = base64.b64encode(CREDENTIAL1.encode('ascii')).decode('ascii')
headers1 = {"Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Basic '+auth}
SHOP1 = 'name of store1 i.g. example1.myshopify.com'
base1 = f'https://{SHOP1}/admin/api/{API_VERSION}/'
API_KEY2 = "API_KEY for private app of store 2")
PASSWORD2 = "PASSWORD for private app of store 2")
CREDENTIAL2 = f'{API_KEY2}:{PASSWORD2}'
auth = base64.b64encode(CREDENTIAL2.encode('ascii')).decode('ascii')
headers2 = {"Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Basic '+auth}
SHOP2 = 'name of store2 i.g. example2.myshopify.com'
base2 = f'https://{SHOP2}/admin/api/{API_VERSION}/'
# example call to the first store
r1 = requests.get(base1+'products/count.json',headers=headers1)
# example call to the second store
r2 = requests.get(base2+'products/count.json',headers=headers2)

Related

Send list to server without json_encode dart

Iam using http package to communicate with the server.
How to send an list to php file in the server without json_encode in Dart with Flutter.
dynamic result = null;
List ids = [12, 65, 7];
Map data = {
'name': 'Mark',
'ids': ids,
};
var client = new http.Client();
await client.post('https://example.com/control/',
headers: {
"Accept": "application/json",
},
body: data,)
.then((response) => result = jsonDecode(response.body));
My code above dont work, The problem is I need to write json_encode(ids) to send the data, and when I want to get the array/list in my php file I need to write json_decode($this->input->post('ids'))
How to solve it without json_encode and json_encode, how to send an json object which can accept arrays without any problem?
I don't understand completely what is the problem with sending json but you may convert your list to string like:
final idsSerialized = ids.map((id) => '$id').join(',');
Then send this string as payload of POST request to php script which can read value via _POST array (or your favorite way) and restore this serialized string to array:
$ids = explode($_POST['ids'], ',');

Passing same value to multiple tasks in locust

We have a requirement where we need to send a post request and then send a delete request for the same end point(REST API).
Need to generate a unique id for each post request, for each user in each iteration.
generated unique string is put inside on_start() method of task class (SequentialTaskSet).
Problem is, it runs for one iteration, but generates same id for consecutive iterations for each user.
To get unique id for each user in each iteration, generating the unique string within the task itself works, but issue here is, I could not pass the same Id to next task where I need to send delete request.
This is what code looks like now:
class StudentClass(SequentialTaskSet):
rndString = None
def on_start(self):
self.rndString = str(uuid.uuid4())
#task
def postRequest(self):
endpoint = "/students"
headers = {
'Authorization': 'Bearer token',
'content-type': 'application/json', 'accept': 'application/json'
}
data = {
"Id": f'std-{self.rndString}',
}
with self.client.post(endpoint, name="Post request", headers=headers, data=json.dumps(data),
catch_response=True) as response:
........
Appreciate any help in achieving this.
I think if you don't need to call post and delete requests with different weights you can do both calls in same task. Is there something I am missing that requires you to separate tasks for post and delete calls? If yo do need to separate them you can update the self.rndString in post task and it will use the updated one in delete.
#task(1)
def hello_world(self):
response = self.client.get("/listing")
print(response.text)
#task
def fill_crud(self):
response = self.client.post('/api/fill_post/', {"number_1": 76, "number_2": 897, "number_3": 564, "text_4": "Sneha"})
print(response.status_code)
res = json.loads(response.text)
response_id = (res['id'])
response_put = self.client.put(f'/api/fill_post/{response_id}/', {"number_1": 76576, "number_2": 89657, "number_3": 5654, "text_4": "Sneha"})
response_patch = self.client.patch(f'/api/fill_post/{response_id}/', {"text_4": "Suveksha"})
response_delete = self.client.delete(f'/api/fill_post/{response_id}/')
You can try it in this way, I hope it will helps anyone.

How to use REST in python to delete multiple IDs in interation?

I am trying to create a script that will do a GET request to retrieve data and then output it so that it can be referenced in the DELETE request URL to run through and delete all the data.
Code:
url = "https://192.168.0.1/api/3/asset_groups/443/assets"
payload = {}
headers = {
'Authorization': 'Basic',
"Accept": "application/json"
}
data = requests.get(url, headers=headers, data = payload, verify=False).text
output = json.loads(data)
#Attempting to delete assets by resource field
for resources in output['resources']:
print(resources)
Would I be able to somehow get the resources to be referenced as the id part in the DELETE request
URL:
"https://192.168.0.1/api/3/asset_groups/443/assets/{assetId}"
The resources field just outputs the IDs of the assets I retrieved as such:
102695
105759
105761
The list is much longer than just these 3 and is never a set amount. Will always vary hence why I would like it to iterate until all are deleted.

http.post is being fired twice

I am a bit new to Flutter, and I am building a screen that posts data to an API built in PHP mon my hosting server. The API is built by me which receives a JSON object and then saves the data.
The app is working fine, and API is receiving the data, but the http.post seems is firing twice ( calling the API twice)
Which makes my API saves the record twice. there is no possible way for me to check before adding the send record. as My API simply saves a new record so whenever it receives a call it simply saves it and returns back a value for the mobile App ( built in Flutter).
If I use a condition to check, this way the first call will return correct data to the mobile app, but the second one will return an error for the mobile app since the record already exists.
I have read about the Access-Control-Allow-Origin and how it might be the issue and put it my my .httaccess file
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
but no luck.
any idea.
Note I am using a shared hosting.
Code I use in Flutter:
class _PostADToServerState extends State<PostADToServer> {
Future<List<JSBResponse>> _postRequest() async {
// print('Call API function is called');
Map<String, dynamic> myAd = {
"isbn10": widget.title.isbn10,
"isbn13": widget.title.isbn13,
... [Some fields]
"titleCondition": widget.title.titleCondition,
"priceIs": widget.title.priceIs,
"school_name": widget.title.schoolName
};
String json = jsonEncode(myAd);
var url = 'https://www.example.com/xapis/save_new_ad.php';
var body = json;
var data = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: body);
var jsonData = jsonDecode(data.body);
Code in my PHP API starts with the following:
$data = file_get_contents('php://input');
$theTitle = json_decode($data);
Then I use the content I find in the $theTitle object as the following:
$title = $theTitle->title;

How to export 15000+ Google Group members?

There are around 15000+ members in my Google Group and I'd like to export them to CSV file. Google Groups says there are too many to export Is there any other way to export all the 15000+ members?
This is possible using the Directory API. You can see how to set up a project in the Google Developer's Console with the appropriate scopes here. I have a sample of code below that shows how I did this for my email list manager (written in Python3). Note that mine just outputs to a list, but you could write to a csv as well.
import urllib.request, urllib.parse, urllib.error
import json
req = urllib.request.Request("https://www.googleapis.com/admin/directory/v1/groups/%s/members" % (group.replace("#", "%40").replace(".", "%2E")))
req.add_header("Authorization", "Bearer %s" % (authToken))
rawResponse = urllib.request.urlopen(req)
fResponse = json.loads(rawResponse.readall().decode('utf-8'))
if "members" in fResponse:
curMembers = fResponse["members"]
while "nextPageToken" in fResponse:
req = urllib.request.Request("https://www.googleapis.com/admin/directory/v1/groups/%s/members?pageToken=%s" % (group.replace("#", "%40").replace(".", "%2E"), fResponse['nextPageToken']))
req.add_header("Authorization", "Bearer %s" % (authToken))
rawResponse = urllib.request.urlopen(req)
fResponse = json.loads(rawResponse.readall().decode('utf-8'))
if "members" in fResponse:
curMembers.extend(fResponse["members"])
You'll need to define a way to retrieve the oauth2 authentication token (authToken in the above snippet). I do so as below, but there are dedicated libraries for this (just not for Python3 that I know of):
def RenewToken():
"""
This function retrieves an authentication token from Google which will allow the script
to view and edit group membership
"""
clientID = "client_id.apps.googleusercontent.com"
clientSecret = "client_secret"
grantType = "refresh_token"
responseType = "code"
refreshToken = "refresh_token"
requestDict = {"client_secret": clientSecret, #field-value pairs for the request body
"grant_type": grantType,
"refresh_token": refreshToken,
"client_id": clientID}
requestUri = "https://accounts.google.com/o/oauth2/token"
requestString = urllib.parse.urlencode(requestDict)
requestBody = requestString.encode('utf-8')
request = urllib.request.Request(requestUri, data=requestBody)
response = urllib.request.urlopen(request)
responseDict = json.loads(response.readall().decode('utf-8'))
return responseDict['access_token']
You can get client_id, client_secret and refresh_token from the Google developer's console for your project.
you can export all contacts in your google group in a Google Spreadsheet
link : https://developers.google.com/apps-script/reference/groups/
After you can create a trigger to add new contact dynamically, and export you Google spreadsheet on a cvs's file.
you can create this solution quickly and simple.