I need to update python script to work with additional data which are not there at the moment. Hence the use of "requests" but somehow it's not working for me.
Basically I need python version of below curl which is providing data I need e.g.:
curl -X GET -H "Authorization: GenieKey XXXXXXXXXXXXXXX" 'https://api.eu.opsgenie.com/v2/alerts/f013a45e-4227-44bb-a0a7-9b2cb6c7c2d9-1616676741714?identifierType=id'
{
"data":{
"seen":true,
"id":"f013a45e-4227-44bb-a0a7-9b2cb6c7c2d9-1616676741714",
"tinyId":"400",
"alias":"test MP",
"message":"MP testing",
"status":"open",
"acknowledged":true,
"isSeen":true,
"tags":[
"MP testing",
"sre"
],
"snoozed":false,
"count":1,
"lastOccurredAt":"2021-03-25T12:52:21.714Z",
"createdAt":"2021-03-25T12:52:21.714Z",
"updatedAt":"2021-04-16T10:28:18.372Z",
"source":"mail#mail.no",
"owner":"mail#mail.no",
"priority":"P5",
"teams":[
{
"id":"45c719c5-d3e1-4e75-9284-b0c75103d44a"
}
],
"responders":[
{
"type":"team",
"id":"45c719c5-d3e1-4e75-9284-b0c75103d44a"
}
],
"integration":{
"id":"132f80a5-b653-4b8a-ba33-eed59cfd6a0a",
"name":"Default API",
"type":"API"
},
"report":{
"ackTime":1892156658,
"acknowledgedBy":"mail#mail.no"
},
"ownerTeamId":"45c719c5-d3e1-4e75-9284-b0c75103d44a",
"actions":[
],
"entity":"TEST MP",
"description":"popis problemu {{priority}}",
"details":{
"priority2":"jednicka",
"issueKey":"FIXIT-981939"
}
},
"took":0.005,
"requestId":"b1f0f485-b06e-45f2-88c0-fe5809cd1ea9"
}
Part of the python script I need to create looks like this for now:
import requests
from requests.auth import HTTPBasicAuth
# Making a get request
response = requests.get('https://api.eu.opsgenie.com/v2/alerts/f013a45e-4227-44bb-a0a7-9b2cb6c7c2d9-1616676741714?identifierType=id', auth=('Correct ID', 'Correct PW'))
print(response.text) # To print unicode response string
print(response)
Result I am getting:
root#server: pts/0: 2 files -> python3 get_request2.py
<Response [422]>
{
"message":"Key format is not valid!",
"took":0.001,
"requestId":"cc21637d-c864-4ba0-92a6-e454ddb74663"
}
Can you please help to determine why I am not getting the data as it is working from shell via curl? I tried to find similar topics but no solution for working for me. I tried add headers or verify=False but no success. Sensitive info is hidden.
Source data are in JSON if it matters and python version is 3.4.10
Thank you in advance for any advice
Related
I am trying to execute the following cURL command using python script. I want to than save the results as text file.
cURL command:
curl -d #myfile.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx"
Python Script:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx"
payload = {r"C:\Users\Desktop\myfile.json"}
res = requests.post(url, data=payload)
print(res.text)
Error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\myfile.json\n^",
"errors": [
{
"message": "Invalid JSON payload received. Unexpected token.\myfile.json\n^",
"domain": "global",
"reason": "parseError"
}
],
"status": "INVALID_ARGUMENT"
}
}
From the error, i can understand that the way i am providing the json file must be wrong. I tried different ways but error still remains. The json file contain set of parameters required for the API call.
please could any guide here. Also indicate how to save the output as text.
It's close but all you're doing is sending the json file name to the remote HTTP server. You need to open the file first:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx"
with open("C:\Users\Desktop\myfile.json", 'rb') as payload:
res = requests.post(url, data=payload)
print(res.text)
I am currenlty thinkering with the IBMWatson Natural Language Understanding API.
In the official tutorial page it shows the basic curl command to use the api as follows:
curl -X POST -u "apikey:{apikey}" \
--header "Content-Type: application/json" \
--data '{
"url": "http://newsroom.ibm.com/Guerbet-and-IBM-Watson-Health-Announce-Strategic-Partnership-for-Artificial-Intelligence-in-Medical-Imaging-Liver",
"features": {
"sentiment": {},
"categories": {},
"concepts": {},
"entities": {},
"keywords": {}
}
}' \
"{url}/v1/analyze?version=2019-07-12"
The command basicly analyzes the page provided in the url key of data parameter and returns an analysis.
I want to do the same action using Python's requests library, however I am new to it. As far as I've gathered from the web the following format should correspond to the same request:
headers={'Content-Type': 'application/json'}
features = {"sentiment": {},"categories": {},"concepts": {},"entities": {},"keywords": {}}
myData ={
"url": "http://newsroom.ibm.com/Guerbet-and-IBM-Watson-Health-Announce-Strategic-Partnership-for-Artificial-Intelligence-in-Medical-Imaging-Liver",
"features": features
}
d = requests.post(
auth=('apikey','7LNEjCMvP6ZcNShjAkjPob7QSCfIHeZMQkn4Ho3dQgte'),
headers=headers,
data=myData,
url='https://gateway-lon.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2019-07-12'
)
However, the server responds with a "400", which I believe is caused by an error in my format.
I have tested editing my apikey, which resulted in Error code 401 "Unauthorized", as expected. So, I know that I can access the server and get authenticated with my key.
I have tested removing the "headers" parameter, which resulted in 415 "Unsupported Media Type", so the return type has to be JSON I guess.
I am not sure on what I'm doing wrong, and appreciate any kind of help. Thanks.
Take a look at the Python SDK examples for analyze and Text analytics features
in the API reference. They might help.
So first of all thanks, I'm really new to python and I am trying to understand APIs, I'm currently trying to log in into /inventory/json/v/1.4.1/<request_code>?jsonRequest=<json_request_content> which is the Earth Explorer API, and the first step is to Login, and according to the documentation I am supposed to use POST instead of GET, so here is what I got so far, and it works but this is what I
import requests
import requests
user = 'xxxxx'
psword = 'xxxxx'
input_data= {'username':user,'password':psword,'catalogId':'EE'}
test=requests.post('https://earthexplorer.usgs.gov/inventory/json/v/1.4.0/login?jsonRequest=input_data)')
print(test.text)
print(test.status_code)
{
"errorCode": "AUTH_ERROR",
"error": "Passing credentials via URL is not permitted - use a POST request",
"data": null,
"api_version": "",
"access_level": "guest",
"executionTime": 0
}
200
I have no idea what to do, thank you so much. This is the documentation for the earth explorer API, thank you so much https://earthexplorer.usgs.gov/inventory/documentation/json-api?version=1.4.1#login
I have encountered the same problem while working with Earth Explorer API and managed to solve it by reading usgs package code. Basically, the problem is that you must send the request body as a string. That is, your request body must look like this when printed
{
"jsonRequest": "{\"username\": \"???\", \"password\": \"???\", \"catalogId\": \"???\"}"
}
You can achieve this using
import json
import requests
req_params = {
'username': '???',
'password': '???',
'catalogId': '???',
}
req_txt = json.dumps(req_params)
req_body = {
'jsonRequest': req_txt,
}
resp = requests.post('<LOGIN URL HERE>', req_body)
This code is actually taken from usgs package I mentioned, so you should refer to it if you have any additional questions.
I'm struggling with how to properly do this REST API call in Python using requests package.
curl --user aa43ae0a-a7a7-4016-ae96-e253bb126aa8:166291ff148b2878375a8e54aebb1549 \
--request POST --header "Content-Type: application/json" \
--data '{ "startDate": "2016-05-15" , "endDate": "2016-05-16", "format": "tsv", "dataset": "appStart" }' \
https://analytics.cloud.unity3d.com/api/v2/projects/aa43ae0a-a7a7-4016-ae96-e253bb126aa8/rawdataexports
I don't know, how to set the parameters of:
r = requests.post("https://analytics.cloud.unity3d.com/api/v2/projects/aa43ae0a-a7a7-4016-ae96-e253bb126aa8/rawdataexports", ...)
Any help would be appreciated, thanks in advance.
Something like this should do the job :
auth = HTTPBasicAuth('aa43ae0a-a7a7-4016-ae96-e253bb126aa8', '1662[....]549')
payload = {
"startDate": "2016-05-15" ,
"endDate": "2016-05-16",
"format": "tsv",
"dataset": "appStart",
}
url = "https://analytics.cloud.unity3d.com/api/v2/projects/aa43ae0a-a7a7-4016-ae96-e253bb126aa8/rawdataexports"
result = requests.post(url, json=payload, auth=auth)
Authentication : --user argument of curl comand allows to setup an HTTP Basic Auth
--data was a JSON payload, while the requested content-type is configured (via headers) with Content-Type: application/json. Simplify this with requests using json argument and passing a valid python dict as payload. The payload will be converted to json, and the correct header will be added to the request to retrieve a response with json data.
Be careful ! In your question, you provided the user/password used to call this REST API. If this information is the real one, posting it on Stack Overflow is probably a security issue !
I'm building a shell application that allows my teammates to start new projects by running a few commands. It should be able to create a new project and a new repository inside that project.
Although I'm specifying the project key/uuid when creating a new repository, it doesn't work. What I'm expecting is a success message with the details for the new repository. Most of the time, this is what I get:
{"type": "error", "error": {"message": "string indices must be integers", "id": "ef4c2b1b49c74c7fbd557679a5dd0e58"}}
or the repository goes to the first project created for that team (which is the default behaviour when no project key/uuid is specified, according to Bitbucket's API documentation).
So I'm guessing there's something in between my request & their code receiving it? Because it looks like they're not even getting the request data.
# Setup Request Body
rb = {
"scm": "git",
"project": {
"key": "PROJECT_KEY_OR_UUID"
}
}
# Setup URL
url = "https://api.bitbucket.org/2.0/repositories/TEAM_NAME/REPOSITORY_NAME"
# Request
r = requests.post(url, data=rb)
In the code from the api docs you'll notice that the Content-Type header is "application/json".
$ curl -X POST -H "Content-Type: application/json" -d '{
"scm": "git",
"project": {
"key": "MARS"
}
}' https://api.bitbucket.org/2.0/repositories/teamsinspace/hablanding
In your code you're passing your data in the data parameter, which creates an "application/x-www-form-urlencoded" Content-Type header, and urlencodes your post data.
Instead, you should use the json parameter.
rb = {
"scm": "git",
"project": {
"key": "PROJECT_KEY_OR_UUID"
}
}
url = "https://api.bitbucket.org/2.0/repositories/TEAM_NAME/REPOSITORY_NAME"
r = requests.post(url, json=rb)