I am trying to do a request using python. The API uses:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
"$class": "org.acme.model.sensor", \
"sensorId": "1", \
"type": "Temperature", \
"value": "10", \
"timestamp": 1234123 \
}' 'http://localhost:3000/api/sensor'
to create a new sensor. I am trying to do it with python and I have created the proof of concept:
data = {
"$class": "org.acme.model.sensor",
"sensorId": "", #change in the loop with i
"type": "Temperature",
"value": "10",
"timestamp": 382453824
}
header = {
"Content-Type" : "application/json",
"Accept":"application/json"
}
url = "http://localhost:3000/api/sensor"
for i in range(2):
data["sensorId"]=str(i+1)
response = requests.post(url, data=data, headers=header)
#Now I modify the data
data["Temperature"]="50"
response = requests.put(url, data=data, headers=header)
Now, for erasing:
for i in range(2):
url="http://localhost:3000/api/sensor/"+str(i+1)
response = requests.delete(url)
With curl, it works properly but no with the python code. It fails even creating the object.
import requests
import json
header = {
"Content-Type" : "application/json",
"Accept":"application/json"
}
You need to convert your dictionary into a proper format using json.dumps and need to use request.post instead of delete
request_url = 'YOUR_END_POINT'
data = json.dumps(data)
response = requests.post(url=request_url,data=data,headers=headers)
I think that should solve it.
Related
I'm experiencing a strange issue where Python post Requests are hanging, while cURL post requests are working just fine. I'm making a request to the NIH Reporter API.
Here's the Python code that keeps hanging:
headers = {
"accept": "application/json",
"Content-Type": "application/json"
}
data = {
"criteria": {
"award_notice_date": {
"from_date": "2022-06-22",
}
},
"include_fields": [
"ProjectNum",
"ProjectTitle",
"AbstractText",
"AwardNoticeDate"
],
"offset": 14500,
"limit": 500,
"sort_field": "award_notice_date"
}
response = requests.post('https://api.reporter.nih.gov/v2/projects/search', headers=headers, data=str(data))
And here's the cURL equivalent that works:
curl -X POST "https://api.reporter.nih.gov/v2/projects/search" -H "accept: application/json" -H "Content-Type: application/json" -d "{'criteria': {'award_notice_date': {'from_date': '2022-06-22'}}, 'include_fields': ['ProjectNum', 'ProjectTitle', 'AbstractText', 'AwardNoticeDate'], 'offset': 14500, 'limit': 500, 'sort_field': 'award_notice_date'}"
I'm not sure if I'm missing anything. I'm using Python3 as well, and my Requests library is up-to-date with version 2.27.1.
str(data) is not the same as converting it to json. You need to use data=json.dumps(data) or use json=data. Using the latter will also add the "Content-Type": "application/json" header for you, so you could skip that.
I am using Python with Requests module to connect to an EasyRedmine API. I'm having trouble creating a project using the post method in order to post a JSON. It returns "[Unprocessable Entity
<Response [422]>]". I have tried the same request using Postman and Curl and it works perfectly. Does anyone know what could be causing this problem? The following curl command works fine.
curl -X 'POST'
'https://cafte.easyredmine.com/projects.json?key=0224b4238XXXX'
-H 'accept: application/json'
-H 'X-Redmine-API-Key: 0224b4238XXX'
-H 'Content-Type: application/json'
-d '{
"project": {
"easy_external_id": "external-system-1",
"name": "Blue 2",
"homepage": "blue-7",
"description": "I can’t abide these Jawas. Disgusting creatures.",
"author_id": 0,
"is_planned": true,
"easy_is_easy_template": true,
"easy_currency_code": "EUR"
}
This is the methode code:
def create_project(self, name: str, description="", external_id="", homepage="", parent_id="", author_id="",
is_planned= 'false', is_easy_template= "true", start_date="", due_date="", custom_fields=[],
tag_list=[], currency='EUR'):
print(name)
data = {"project": {
"easy_external_id": external_id,
"name":name,
"homepage": homepage,
"description": description,
"parent_id": parent_id,
"author_id": author_id,
"is_planned": is_planned,
"easy_is_easy_template": is_easy_template,
"easy_start_date": start_date,
"easy_due_date": due_date,
"custom_fields": custom_fields,
"tag_list": tag_list,
"easy_currency_code": currency
}
}
endpoint_path = "/projects"
endpoint = f'{self.base_url}{endpoint_path}'
headers = {'X-Redmine-API-Key': f'{self.api_key}',
'accept': 'application/json',
'Content-Type': 'application/json'
}
r = requests.post(endpoint, headers=headers, json= data)
i'm trying to interact with a website's APIs--specifically how to requests.put() a file (JPEG) to it. the Swagger API has a "try it out" function where I successfully can push a file from its "try it out" but when I try to run it in python it throws a 500 internal server error.
this is the successful curl put request from the Swagger "try it out":
curl -X PUT "https://some_website.com/api/v2/documents" -H "accept: /" -H "Content-Type: multipart/form-data" -H "Authorization: Bearer auth tokenp089u098u08j98jasdfsadgfasdg" -d {"file":{},"metadata":"{ "docType":"BILL_OF_LADING", "docTypeNamespace":"platform", "fileType":"IMAGE", "docReferences":{ "name":"bill o lading pal" }, "identifiers":{ "consignment":{ "carrierBookingNumber":"9876smg", "billOfLadingNumber":"1234smg" } } }"}
url = "https://some_website.com"
auth_token = "Bearer auth tokenp089u098u08j98jasdfsadgfasdg"
headers = {"Content-Type": "multipart/form-data",
"Accept": "*/*",
"Authorization": sa_token}
file_loc = "C:/location/of/file/I/want/to/put/Capture.JPG"
metadata = {
"docType":"doc_file",
"docTypeNamespace": "platform",
"fileType":"IMAGE",
"docReferences": {
"name": "this is the form to confirm receipt"
},
"identifiers": {
"consignment": {
"carrierBookingNumber":"9876smg",
"billOfLadingNumber":"1234smg"
}
}
}
body = {
"file": {},
"metadata": metadata
}
resp = requests.put(url=url, headers=headers, data=body)
You should probably send it via json as thats very easy...
import requets
file = "C:\somedir\somedir\somefile.somext"
with open(file, "rb") as f:
fileData = f.read()
putFile(fileD, site, port=3000):
requets.post(site, json='{"file": "' + str(fileD) + '"}'
But you'll need to convert it back to a file.
Trying to re-write shell curl to python script with requests module...
My shell script :
#!/bin/bash
ip=$1
url=https://xxx.xx.xx.com
secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
expand=computerStatus
curl --silent -X POST "$url/api/computers/search?expand=$expand" -H "Content-Type: application/json" -H "api-secret-key: $secret" -H "api-version: v1" -d '{"maxItems": 10,"searchCriteria": [{"fieldName": "hostName","stringTest": "equal", "stringValue": "'"$ip"'"}]}' -k > $file
above works fine in bash.
I am trying to convert to similar python equivalent
What I tried
import json
import requests
import sys
ip = sys.argv[1]
sys_info = []
url=https://xxx.xx.xx.com
secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
expand=computerStatus
headers = {
'Content-Type': 'application/json',
'api-secret-key': secret,
'api-version': 'v1',
}
params = (
('expand', 'expand'),
)
data = '{"maxItems": 10,"searchCriteria": [{"fieldName": "hostName","stringTest": "equal", "stringValue": ip}]}'
response = requests.post('https://url/api/computers/search?expand=expand', headers=headers, params=params, data=data)
print(response)
<Response [400]>
I am getting 400 response.. not sure where i am missing in syntax...
data needs to be a dictionary, try this:
data = {
"maxItems": 10,
"searchCriteria": [{"fieldName": "hostName","stringTest": "equal", "stringValue": ip}]
}
Also convert params to a dictionary as well:
params = {"expand" : expand}
And when posting:
response = requests.post(f'https://{url}/api/computers/search', headers=headers, params=params, data=data)
### or alternatively you can
response = requests.post(f'https://{url}/api/computers/search?expand={expand}', headers=headers, data=data)
So, I try to make a program who tell me the schedule of my bus, i take this real time information on an Api:
https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100385%3A385&stop_point_id=StopPoint%3A59%3A6195786
but when i lunch it there is an error :
"error": "Unknown dataset: tr-vianavigo"
I have a token to use I think but how ?
the Curl for this api is :
curl -X GET --header "Accept: application/json" "https://api-lab-trone-
stif.opendata.stif.info/service/tr-vianavigo/departures?
line_id=100100020%3A20&stop_point_id=59%3A4726914"
when i use the first url on my web browser it work and show me :
[
{
"lineDirection": "Juvisy RER",
"code": "duration",
"time": "12"
},
{
"lineDirection": "Savigny Toulouse-Lautrec",
"code": "duration",
"time": "20"
},
{
"lineDirection": "Juvisy RER",
"code": "duration",
"time": "38"
},
{
"lineDirection": "Savigny Toulouse-Lautrec",
"code": "duration",
"time": "45"
}
]
but in python if i just test :
import requests
#my token
apikey = 'ef169369dfd911b01371b73e975ed88adce881bc92dbbd9720551c94'
#url of the api
url ='https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100385%3A385&stop_point_id=StopPoint%3A59%3A6195786'
#requests
r = requests.get(url, apikey)
print(r.text)
it make the error :
"error": "Unknown dataset: tr-vianavigo"
You must use one of your API keys for this purpose. An API key is obtained via your user account in My API keys. Once generated, the key must be inserted as a query parameter (apikey) in the URL of your
call. For your example:
curl -X GET --header "Accept: application/json" "https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100020%3A20&stop_point_id=59%3A4726914&apikey=<YOUR-API-KEY>"
FYI, the scope of the real-time data available on the dataset tr-unitaire-stif is avalaible here.