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

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.

Related

How to connect to Webservice REST with POST from Power BI

I am trying to connect to a webservice through Power BI but I still do not achieve result, first try to use the Web data source and with the Advanced Use add the Header that in my case is Content-Type and its value is application/json and additional as Body I have a token
Where I get as a result the following:
Additional also try to use as source "Blank Query", where I accessed the advanced editor section and add the following Query:
I get as an error the following:
To make sure that the Webservice works correctly and obtains a result I have used the Advanced REST Client tool and I have made the following configuration:
Where you can see that the Headers section I have added the Header name Content-Type and the value of the Header Value is application/json, in the Body section is where I have added the token
With this I realize that my Webservice gets an answer and that the service is working correctly, I would like someone to give me a little guidance in a short time to perform correctly
Supply the content to switch the method from GET to POST eg
Perform a POST against a URL, passing a binary JSON payload and
parsing the response as JSON.
https://learn.microsoft.com/en-us/powerquery-m/web-contents#example-2
let
url = "https://postman-echo.com/post",
headers = [#"Content-Type" = "application/json"],
postData = Json.FromValue([token = "abcdef"]),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response),
json = jsonResponse[json]
in
json
or
let
url = "https://postman-echo.com/post",
headers = [#"Content-Type" = "application/json"],
postData = Text.ToBinary("{ ""token"":""abcdef""}"),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response),
json = jsonResponse[json]
in
json

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

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)

How to technically send the query parameters to google cloud REST API?

I'm trying to call this REST API
How is one expected to add these params? maxResult
Page token
all
filter
How do I technically send the query parameters?
What part of the payload or options?
I couldn't find an example.
/**
* Checks if dataset already exists in project.
*
* #return {boolean} Returns true if dataset already exists.
*/
function datasetExists() {
// Get a list of all datasets in project.
var url =
'https://bigquery.googleapis.com/bigquery/v2/projects/${projectId}/datasets';
var options = {
method: 'GET',
contentType: 'application/json',
payload: ""
};
var response = authUrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
Logger.log(result);
if (result.entities) {
Logger.log('Dataset with ID = %s created.', dataSet.id);
// return a list of identified entities
return result.entities;
}
All the Google Cloud API use the same definition pattern.
Path parameter, which is in the path of the url, like that
https://bigquery.googleapis.com/xxx/yyy/<pathparameters>/zzz
Query parameters that come in the URL, but at the end, after a ? and separated with &. Most of the time it's tokenPage, pageSize, filters,...
https://bigquery.googleapis.com/xxx/yyy/<pathparameters>/zzz?queryparam1=value1&queryparam2=value2
The body to provide when you perform a POST, PUT, PATCH, DELETE. in JSON (therefore you need to add the content type header when you use it).
Finally, in term of security, the APIs requires a Bearer Access Token in the Authorization header

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.

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;