OPNsense Forum
English Forums => Development and Code Review => Topic started by: FriendOfCarlotta on May 18, 2018, 12:57:23 pm
-
Hello!
I try to add a new route via the api using Python 3 and requests:
apikey = 'xxx'
apisecret = 'xxx'
url = 'https://10.0.0.254/api/routes/routes/addroute'
requests.post(url, data=payload, verify=None, auth=(apikey, apisecret))
payload is
{'route': {'network': '10.0.50.0/24', 'gateway': {'Null4': {'value': 'Null4 - 127.0.0.1', 'selected': 0}, 'Null6': {'value': 'Null6 - ::1', 'selected': 0}, 'VLAN_GW': {'value': 'VLAN_GW - 10.0.0.253', 'selected': 1}, 'WAN_DHCP': {'value': 'WAN_DHCP - 192.168.107.2', 'selected': 0}}, 'descr': 'vlan50', 'disabled': '0'}}
As result I receive:
{"errorMessage":"Error at /usr/local/opnsense/mvc/app/models/OPNsense/Routes/Route.php:59 - Undefined index: (errno=8)"}
On the other side I am able to change an existing route via /api/routes/routes/setroute/<uuid>
with the same payload.
The payload has been received with getroute
and was modified accordingly.
Any hints are appreciated.
Regards, Thomas
-
Just change the gateway field to the name you want as a string. Also the JSON keys/values should be in double quotes:
payload = '{"route": {"network": "10.0.50.0/24", "gateway": "LAN_DHCP", "descr": "vlan50", "disabled": "0"}}'
200 OK
{ "result": "saved" }
-
Thanks for the reply.
In fact I tried this syntax already. But I only get <Response [200]>
as feedback and the route does not show up in the ui. :-\
How do I get a more verbose response?
-
The API is not verbose and always returns 200 (except when an exception is thrown). You have to check the response body for the JSON result.
-
Ok, thanks so far. I'll check this after the holiday. 8)
-
How do I get a more verbose response?
This works for me:
#/usr/bin/python
# import libraries
import json
import requests
# define endpoint and credentials
api_key = ''
api_secret = ''
url = 'https://127.0.0.1/api/routes/routes/addroute'
headers = {'content-type': 'application/json'}
payload = '{"route": {"network": "10.0.50.0/24", "gateway": "LAN_DHCP", "descr": "vlan50", "disabled": "0"}}'
# Make the api call
r = requests.post(url, data=payload, verify=False, auth=(api_key, api_secret), headers=headers)
# Check response
if r.status_code == 200:
print r.text
response = json.loads(r.text)
if response['result'] == 'saved':
print ('The payload was successfully saved !')
print (response['result'])
else:
print ('Connection / Authentication issue, response received:')
print r.text
-
Thanx! The headers parameter does the trick. :-)