I'm trying to communicate with a server (program controlling robots) via webAPI which expects JSON Files. I tried to realize this with the following Python Code, but I always get the Error:
The requested route [/v1/TransportOrders/Order-0001] has not been mapped in Spark for Accept: [/]
Does anybody know what causes the error or how to fix it?
Let me know if you need any further details.
Thanks
CODE:
#!/usr/bin/env python
import requests
import json
url = 'http://localhost:55200/v1/TransportOrders/Order-0001'
# headers= {'Content-type': 'application/json'}
transportOrders = {
"deadline": "2019-03-07T06:42:40.396Z",
"intendedVehicle": "Vehicle-0001",
"destinations": [
{
"locationName": "Location-0001",
"operation": "NOTHING",
}
]
}
resp = requests.post(url, data=json.dumps(transportOrders))
print 'data sent'
if resp.status_code != 200:
print 'error accured transmitting data'
print resp.status_code
The requested route [/v1/TransportOrders/Order-0001] has not been mapped in Spark for Accept: [/]
This is the default "404" message from SparkJava. You should double-check in the server API documentation that you are calling the right end point, at the right path with the right parameters and headers - and the right server, for that matter.
Related
While trying to configure a script using python to write comments using the API i'm encounteringthe following error mesage:
{"error":"Unknown API endpoint."}
The code given by NagiosXI API System Reference, system/corecommand is the following:
curl -XPOST "http://192.168.1.239/nagiosxi/api/v1/system/corecommand?apikey=<API_Key>" -d "cmd=ADD_HOST_COMMENT;localhost;1;%user%;This is a test comment"
This translated to python should be something like this:
import requests
url = "http://192.168.1.239/nagiosxi/api/v1/system/corecommand"
api_key = "<API_Key>"
params = {
"cmd": "ADD_HOST_COMMENT",
"host_name": "localhost",
"entry_time": 1,
"author": "%user%",
"comment_data": "This is a test comment",
"apikey": api_key
}
response = requests.post(url, params=params)
if response.status_code == 200:
print("Comment added successfully")
else:
print("Error adding comment: ", response.text)
At the moment i'm getting a 200 response but with the error message previously mentioned: "{"error":"Unknown API endpoint."}"
Currently using NagiosXI version 5.9.3
Both systems are on the same network an "GET" request go through without any hiccups.
Many thanks in advance;
I am trying to connect to a very closed source database system via REST API to pull some data. The API so weird that it just gives you status code 400 & nothing much. No information or error pointing to what is wrong with the provided data. I am calling this API using postman & it is giving me proper response but when I use Python's requests lib to call this API I am getting 400 status (Which means there is something wrong with the provided data with the request).
This is my code.
def pull_data():
url = construct_url(configs.get("get_data_path"))
payload = json.dumps([
{
"SampleInterval": 600000,
"GetEnum": False,
"ResampleMethod": "Around",
"MinimumConfidence": 0,
"MaxRows": 100,
"TimeFormat": 6,
"ReductionData": "avg",
"TagName": [
"NC_AI3",
"NC_AI32"
],
"StartTime": "05/16/2022 08:49:26.000",
"EndTime": "05/16/2022 13:03:36.000",
"OutputTimeFormat": 6,
"EventSequence": 0
}
])
headers = {'Content-Type': 'application/json'}
res = requests.post(url, json=payload, verify=False, auth=HTTPBasicAuth(configs.get("user"), configs.get("password")), headers=headers)
print("----------", "Status Code", res.status_code, "-------")
I think somehow the json data sent via the request.post method is not getting recognised by the API. I think it is something to do with the fact that I am sending list of dict as json error not a usual dict as we do or see everywhere.
Can please someone tell if I am sending the json data correctly or not or is there any other way to do it?
Best wishes (first things first!)
I want to enable/disable a PoE port on my UniFi switch. For this I aim using Python 3.9.1 (first time) with the following code:
import requests
import json
import sys
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
gateway = {"ip": "MYSERVER.COM", "port": "8443"}
headers = {"Accept": "application/json", "Content-Type": "application/json"}
login_url = f"https://{gateway['ip']}:{gateway['port']}/api/login"
login_data = {
"username": "MYUSERNAME",
"password": "MYPASSWORD"
}
session = requests.Session()
login_response = session.post(login_url, headers=headers, data=json.dumps(login_data), verify=False)
if (login_response.status_code == 200):
api_url_portoverrides = 'api/s/default/rest/device/MYDEVICEID'
poe_url = f"https://{gateway['ip']}:{gateway['port']}/{api_url_portoverrides}"
# build json for port overrides
json_poe_state_on = '{"port_overrides": [{"port_idx": 6, "portconf_id": "MYPROFILE1"}]}'
json_poe_state_off = '{"port_overrides": [{"port_idx": 6, "portconf_id": "MYPROFILE2"}]}'
post_response = session.put(poe_url, headers=headers, data=json.dumps(json_poe_state_off))
print('Response HTTP Request {request}'.format(request=post_response.request ))
else:
print("Login failed")
The login works (I get the 2 security cookies and tried them in Paw (a macOS REST API client) to see if these were ok)) but the second call, the. PUT, returns OK but noting happens.
Before I've done this in Python, I tried all my calls in Paw first and there it works. I tried everything in bash with curl and there it works too. So I am a bit at a loss here.
Anyone has an idea?
Thank you for your time!
Best regards!
Peter
Solved it! By looking into what was posted with Wireshark I saw that the payload was different. The culprit was the json.dumps function which encoded the string by putting a backslash in front of each double quote.
It works now!
I have a node.js API as below to which I send a POST request from python as below,the issue am facing is if I remove the
headers={"Content-Type": "application/json"} the POST goes thorugh,if not i get a Read timed out. error, can anyone provide guidance on how to fix this timeout error ?
node.js endpoint
app.post("/api/bats_push",(req, res) => {
//console.log("Calling bats_push...")
const d = {
method: req.method,
headers: req.headers,
query: req.query,
body: ''
}
req.on('data', (c) => {
//console.log(c)
d.body = d.body + c
});
req.on('end', () => {
DATA.push(d);
res.end('Saved BATS job details');
//res.status(200).json({
//message: "Saved BATS job details",
//posts: req.body
//});
});
});
Python POST
try:
json"},timeout=10.0)
r = requests.post(webhook_url,data=json_data.encode("utf8"),verify=False,headers={"Content-Type": "application/json"})
print "posted"
print(r.status_code, r.reason)
print r.url
print r.text
except Exception as e:
print (e)
Error:-
InsecureRequestWarning)
HTTPSConnectionPool(host='company.com', port=443): Read timed out. (read timeout=10.0)
I seems that you are using express.js. I believe that your problem is, that body is actually already parsed. You can check it by reading req.body. The situation is caused because express.js already read whole body (due to the content type) and trying to read body again will cause timeout (event data and event end are not emitted).
There are several ways how to fix it.
disable express.js body parser - or reconfigure it to ignore json
remove reading body code and use directly req.body
app.post("/api/bats_push",(req, res) => {
//console.log("Calling bats_push...")
const d = {
method: req.method,
headers: req.headers,
query: req.query,
body: req.body
}
DATA.push(d);
res.end('Saved BATS job details');
});
according to requests why not use this:
#replace this
r = requests.post(webhook_url,data=json_data.encode("utf8"),verify=False,headers={"Content-Type": "application/json"})
#by this...assuming that 'data' is a dict
r = requests.post(webhook, json=data, verify=False)
Looks like it could be something related to your SSL.
Check if you get the same error sending a request to your localhost with the server running.
From your question,the key word is:
if I remove the headers={"Content-Type": "application/json"} the POST goes thorugh.
The reason may clear:it is a wrong way use about the header.
Simpler say: the node.js app check the header before into the logic code.
if do not send the header by ourself,the requests part use the default headers below:
{
'User-Agent': 'python-requests/2.22.0',
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*',
'Connection': 'keep-alive',
}
through the requests's code can print the default headers when post.
you just use the header
{"Content-Type": "application/json"}
may resulting in the node.js app think the reqeust not legitimate(the word I do not know how to explain in English).
If the node.js app is developed by yourself, you can try to find the frame's check after create a tcp connection and before the logic code,the way is to read the source code.
If the node.js app is not developed by yourself,try to change the header mixing the default header to find which header key checked by the node.js app.
But in my thought,It is import ,about the node.js app's interface description:
we just use by interface description engouth,just need to know the error from the api header's check, which the description should show but not show to us?
Hope to help you.
I'm working on a simple command-line Pushbullet Python project, and have the following code:
from settings import *
import urllib
import urllib2
def pushSms(number, message):
url = 'https://api.pushbullet.com/v2/ephemerals'
values = {
"type": "push",
"push": {
"type": "messaging_extension_reply",
"package_name": "com.pushbullet.android",
"source_user_iden": settings["PUSHBULLET_USER_IDEN"],
"target_device_iden": settings["PUSHBULLET_SMS_IDEN"],
"conversation_iden": number,
"message": message
}
}
headers = {"Authorization" : "Bearer " + settings["PUSHBULLET_API_KEY"]}
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
return response
Example usage might be pushSms("555 555 5555", "Hi there!").
This takes advantage of the Pushbullet android app access to SMS, as documented here. I've checked my settings variables and they're all valid (in fact, they're currently in use in a JavaScript version of nearly this exact code in another project of mine.
My suspicion is that this is a basic Python syntax/urllib2 misuse or error, but I've been staring/Googling for hours and can't see my error. Thoughts?
I can't tell for certain (the response from the server may contain more information), but because we accept both form encoded and json requests, you probably need to set the header "Content-Type: application/json" on the request.
If that's not the case, could you post the body of the 400 response?