Hi folks,
I am able to use the API in order to fetch information, but i am failing to add new items and i think my problem is how to add the payload to POST requests..
Here is my Code, wich just gets a `{'result': 'failed'}` back, but i have no idea why it fails. do i need another Content-Type Header?
I am able to use the API in order to fetch information, but i am failing to add new items and i think my problem is how to add the payload to POST requests..
Here is my Code, wich just gets a `{'result': 'failed'}` back, but i have no idea why it fails. do i need another Content-Type Header?
Code Select
import requests
import json
from requests.auth import HTTPBasicAuth
import os
# OPNsense API
#https://opnsense.local/api/<module>/<controller>/<command>/[<param1>/[<param2>/...]]
# Globale Konfiguration
API_KEY = os.getenv('API_KEY')
API_SECRET = os.getenv('API_SECRET')
OPNSENSE_URL = "https://10.1.1.11:8443"
INIT_DATA = {
'vlan': {
"vlanTag": "211",
"interface": "lagg0",
"description": "newVLAN"
}
}
def send_request(url, data=None, method='POST'):
headers = {}
auth = HTTPBasicAuth(API_KEY, API_SECRET)
verify_ssl = False # Für Produktionscode sollten Sie SSL-Zertifikatsprüfung aktivieren
if method in ['POST', 'PUT', 'PATCH']:
headers['Content-Type'] = 'application/xml'
response = requests.post(url, headers=headers, data=json.dumps(data), auth=auth, verify=verify_ssl)
else:
response = requests.get(url, headers=headers, auth=auth, verify=verify_ssl)
if response.ok:
return response.json()
else:
response.raise_for_status()
def add_vlan(vlan_data):
"""Adds a new VLAN."""
url = f"{OPNSENSE_URL}/api/interfaces/vlan_settings/addItem"
# Erstellen der XML-Payload mit den übergebenen Werten
xml_payload = f"""
<vlan>
<if>{vlan_data['interface']}</if>
<tag>{vlan_data['vlanTag']}</tag>
<pcp>0</pcp>
<proto></proto>
<descr>{vlan_data['description']}</descr>
<vlanif>vlan0{vlan_data['vlanTag']}</vlanif>
</vlan>
"""
print(xml_payload)
# Senden des Requests mit der XML-Payload
response = send_request(url, xml_payload)
return response
# Main function to organize operations
def main():
response = add_vlan(INIT_DATA['vlan'])
print (response)
if __name__ == "__main__":
main()
"