fortiswitchos rest api - docs.fortinet.com 3.4.0 api... · table of contents changelog 4...
TRANSCRIPT
FORTINET DOCUMENT LIBRARY
http://docs.fortinet.com
FORTINET VIDEO GUIDE
http://video.fortinet.com
FORTINET BLOG
https://blog.fortinet.com
CUSTOMER SERVICE & SUPPORT
https://support.fortinet.com
http://cookbook.fortinet.com/how-to-work-with-fortinet-support/
FORTIGATE COOKBOOK
http://cookbook.fortinet.com
FORTINET TRAINING SERVICES
http://www.fortinet.com/training
FORTIGUARD CENTER
http://www.fortiguard.com
END USER LICENSE AGREEMENT
http://www.fortinet.com/doc/legal/EULA.pdf
FEEDBACK
Email: [email protected]
Monday, November 16, 2015
FortiSwitch-3.4.0 API Guide
TABLE OF CONTENTS
Change Log 4Introduction 5
REST API Background 5Authentication 5Setting up Authentication Session 5CSRF Tokens 6API HTTP Response Codes 7
CMDB API 8URL Format 8Paths and Names 8Get Schema 9List of Methods 9Additional Parameters (Collection) 10Additional Parameters (Individual Resource) 10Python Examples 11
Basic setup (use this code for each example) 11Retrieve anObject 11Add anObject 12Update anObject 12Move anObject 12Delete anObject 13
Monitor API 14List of Methods 14Python Examples 16
Basic setup (use this code for each example) 16Retrieve port state 16Retrieve ACL statistics 16Retrieve loop-guard state 17
Change Log
Change Log
Date Change Description
11/16/2015 API for FortiSwitchOS 3.4.0 release.
4 FortiSwitchOSREST APIFortinet Technologies Inc.
Introduction REST API Background
Introduction
This document provides information about the REST APIs supported in FortiSwitchOS starting in release 3.4.0.
FortiSwitch supports the following REST APIs:
CMDB API - creation, modification and retrieval of configured objects and collections
Monitor API - retrieval of dynamic state and statistics
API responses include data in JSON format. Each API response also includes an HTTP response code, toindicate the success or failure of the operation.
REST API Background
ARESTful API provides interactions between a client and a server, using the HTTP protocol.
The API is stateless - each request is independent. Requests use standard HTTP methods (Get, Post, Put,Delete).
The following operations are supported by a RESTful API:
l Fetch data by sending a GET requestl Add data by sending a POST requestl Update data by sending a PUT requestl Delete data by sending a DELETE request
GET, PUT and DELETE are idempotent. The operation will produce the same result no matter how many times itis repeated.
Authentication
To initiate requests to the FortiSwitch REST API, you will need the following:
l A valid authentication token.l Appropriate permissions to access the requested object.l A valid CSRF token
l required for for HTTP POST/PUT/DELETEmethodsl HTTPGET does not require a CSRF token
Setting up Authentication Session
To acquire a valid authentication token, you must send a POST request to the FortiSwichOS login handler. Therequest must include your administrative login name and password.
The POST names for these fields are 'username' and 'secretkey' respectively.
FortiSwitchOSREST APIFortinet Technologies Inc.
5
CSRF Tokens Introduction
For example, the following Python code sets the username as 'admin' and an empty password (the default login):
import requests, json, cookieliburl_login=https://10.105.4.16/logincheckclient = requests.session()
#Login requestpayload = "username=admin&secretkey="r = client.post(url_login, data=payload, verify=False)
If the login is successful, the response will contain the authentication token in the APSCOOKIE cookie value. Thiscookie value must be included in any subsequent API requests.
CSRF Tokens
Cross-Site Request Forgery (CSRF) Tokens are alphanumeric values that are passed in the messages betweenclient and server to ensure that a user's form submission does not originate from an offsite document.
The CSRF token must be included in the POST data with the name CSRF_TOKEN, or in the X-CSRFTOKENHTTP header. The value for the token is included as a hidden input named csrftoken on any form renderedby the GUI. It's also available from the cookie variable ccsrftoken.
Continuing the example python above, extract the token from cookie in the following way (‘r’ is the response tothe post request for the login handler):
apscookie=r.cookies
for cookie in client.cookies:if cookie.name == 'ccsrftoken':
csrftoken = cookie.value[1:-1] # token stored as a list
client.headers.update({'X-CSRFTOKEN': csrftoken})
print csrftoken
Please note that the ccsrftoken cookie variable is only used to pass the token value from the server to theclient, it will not be used to authenticate the request. For authentication, the token must be in the POST data orHTTP headers.
6 FortiSwitchOSREST APIFortinet Technologies Inc.
Introduction API HTTPResponse Codes
API HTTP Response Codes
The API returns an HTTP status code to indicate the disposition of the request. The API uses the followingHTTP status codes:
200 Status ok Request successful
400 Bad request Bad request
403 Forbidden Request is missing the CSRF token or administrator is missing access profilepermissions.
404 Not Found Unable to find the specified resource
405 Method Not Allowed Specified HTTPmethod is not allowed for this resource
413 Request Entity TooLarge
424 Failed Dependency
500 Internal Server Error
FortiSwitchOSREST APIFortinet Technologies Inc.
7
URL Format CMDBAPI
CMDB API
Use the CMDBAPI for creation, modification and retrieval of configured objects and collections on theFortiswitch.
URL Format
The CMDB API supports the following actions:
l Retrieve one resource, or a collection of resourcesl Create a new resourcel Modify a resourcel Move a resourcel Delete a resource, or a collection of resources
The URL for the CMDB API has the following format:
https://<switch_ip>/api/v2/cmdb/<path>/<name>/[<mkey>]
For example,use the following URL to retrieve all of the configured ACL policies:
https://10.105.4.16/api/v2/cmdb/switch.acl/policy/
where path is “switch.acl”, name is "policy" and mkey is blank.
Use the following URL to retrieve ACL policy 100:
https://10.105.4.16/api/v2/cmdb/switch.acl/policy/100
where path is “switch.acl”, name is "policy", and mkey is 100
Paths and Names
The paths and names for the URL reflect the CLI command tree. Refer to the FortiSwitch CLI Reference forassistance with the command tree structure.
For information about the structure of each object or collection, use the tree command in the CLI, or use theAPI get schema action (explained in the next section).
8 FortiSwitchOSREST APIFortinet Technologies Inc.
CMDBAPI Get Schema
Get Schema
The CMDBAPI supports the ability to retrieve the schema for any collection or individual object.
The URL format includes the path and name that you want to retrieve, and set the optional action parameter tobe schema.
For example use the following URL to retrieve the schema for ACL policy
https://10.105.4.16/api/v2/cmdb/switch.acl/policy/?action=schema
List of Methods
The following table describes the HTTP methods that are available for collections and individual resources.
Some of the methods can be modified with the optional action parameter.
In addition to the action parameter, there are additional parameters that apply to specific methods. These aredescribed in the subsequent two sections Additional Parameters (Collection) and Additional Parameters(Individual Resource).
Type HTTPMethod Action Summary Return Type
Collection GET Response includes all entries in the specifiedtable.
Array
GET default Returns the default values for this object type. Object
GET schema Returns the schema for this object type. Object
POST Add a new entry to the table.
DELETE Delete all of the objects in the specified table.
Resource GET Response includes the specified entry in thetable. Object
PUT Modify the fields in a table entry.
PUT move Move an entry to a new position in the table.
POST clone Add a new entry by cloning the specified existingentry.
DELETE Delete an entry in the table.
FortiSwitchOSREST APIFortinet Technologies Inc.
9
Additional Parameters (Collection) CMDBAPI
Additional Parameters (Collection)
Some of the API methods for retrieving or modifying entries in a collection can also take additional optionalparameters.
Get
There are optional parameters you can set when retrieving entries by using the GET command for a collection.
The following table describes the parameters that apply to the GET command for a collection:
Parameter Type Description
datasource boolean Enable this parameter to include datasource information for eachlinked object.
Additional Parameters (Individual Resource)
Some of the API methods for retrieving or modifying individual resources can also take additional optionalparameters.
Get
You can specify the following additional parameters in the GET command for a resource. These parametersmodify the information that will be returned for this entry:
Parameter Type Description
datasource boolean Include datasource information for each linked object.
Put (action=move)
To move a resource, you must specify where to move it (ie. before record X or after record Y). Specify one thefollowing parameters to move a resource:
Parameter Type Description
before string The ID of an existing resource. This resource to be moved will beplaced before the resource with this ID.
after string The ID of an existing resource. This resource to be moved will beplaced after the resource with this ID.
10 FortiSwitchOSREST APIFortinet Technologies Inc.
CMDBAPI Python Examples
Post (action=clone)
To clone a resource, you must specify the ID for the new resource. Specify the following parameter to clone anexisting resource:
Parameter Type Description
nkey string A new unique ID for the new resource to be created.
Python Examples
The following snippets of Python code provide examples of how to use the CMDB API.
Basic setup (use this code for each example)The following example shows how to log in to the API, retrieve the CSRF token, and set the CSRF token in theclient header.These are basic actions that are required before invoking any other methods on the API.
url_login="https://192.168.1.99/logincheck"client = requests.session()
#Login requestpayload = "username=admin&secretkey="r = client.post(url_login, data=payload, verify=False)
apscookie=r.cookies
for cookie in client.cookies:if cookie.name == 'ccsrftoken':
csrftoken = cookie.value[1:-1] # token stored as a list
client.headers.update({'X-CSRFTOKEN': csrftoken})
Retrieve an ObjectThe following example shows how to send an HTTP get request to retrieve the values of a provisioned object(ACL 100 in this example).
url_cmdb="https://192.168.1.99/api/v2/cmdb/switch.acl/policy/100"r = client.get(url_cmdb, cookies=apscookie, verify=False)print r.text
The following example shows how to retrieve the port data values for port2:
url_cmdb="https://192.168.1.99/api/v2/cmdb/switch/physical-port/port2"r = client.get(url_cmdb, verify=False)print r.text
FortiSwitchOSREST APIFortinet Technologies Inc.
11
Python Examples CMDBAPI
The following example shows how to retrieve the log memory settings:
url_cmdb="https://192.168.1.99/api/v2/cmdb/log.memory/setting/"r = client.get(url_cmdb, verify=False)print r.text
Add an ObjectThe following example shows how to add a provisioned object (ACL 100 in this example). The record to be addedis encapsulated using JSON notation and sent in an HTTP post request.
url_acl_post="https://192.168.1.99/api/v2/cmdb/switch.acl/policy/"
payload = {'json':{'id':'100', 'ingress-interface':[{'member-name':'port11'}],'classifier':{'dst-ip-prefix':'11.11.11.110/32'}, 'action':{'drop':'enable'}}}
r = client.post(url_acl_post, data=json.dumps(payload), cookies=apscookie, verify=False)print r.json
Update an ObjectTo update an object, you must provide name+value pairs for the fields that you are changing. The other fields inthe provisioned object retain their current values.
The following example shows how to update a provisioned object (ACL 100 in this example).
url_acl_put="https://192.168.1.99/api/v2/cmdb/switch.acl/policy/100"
payload = {'json':{'ingress-interface':[{'member-name':'port12'}], 'classifier':{'dst-ip-prefix':'12.12.12.110/32'}, 'action':{'drop':'enable'}}}
r = client.put(url_acl_put, data=json.dumps(payload), cookies=apscookie, verify=False)print r.json
The following example shows how to enable STP on port 48:
url_sw_stp="https://192.168.1.99/api/v2/cmdb/switch/interface/port48"payload = {'json':{'stp-state':'enabled'}}r = client.put(url_sw_stp, data=json.dumps(payload), cookies=apscookie, verify=False)
The following example shows how to disable the log memory setting:
url_sw_log="https://192.168.1.99/api/v2/cmdb/log.memory/setting/"payload = {'json':{ 'status': 'disable'}}r = client.put(url_sw_log, data=json.dumps(payload), cookies=apscookie, verify=False)
Move an ObjectThe following example shows how to move an object within a collection. Specify the object to be moved in theURL, and specify where to move the object in the action command. This example moves ACL 200 before ACL100 in the ACL collection:
url_acl_move="https://192.168.1.99/api/v2/cmdb/switch.acl/policy/200"payload = {'action':'move','before':'100'}r = client.put(url_acl_move, params=payload, cookies=apscookie, verify=False)print r.text
12 FortiSwitchOSREST APIFortinet Technologies Inc.
CMDBAPI Python Examples
Delete an ObjectThe following example shows how to delete an object in a collection. Specify the object to be deleted in the URL.This example deletes ACL 100 in the ACL collection:
url_acl_post="https://192.168.1.99/api/v2/cmdb/switch.acl/policy/100"r = client.delete(url_acl_post, cookies=apscookie, verify=False)print r.text
FortiSwitchOSREST APIFortinet Technologies Inc.
13
List of Methods Monitor API
Monitor API
The Monitor API supports retrieval of dynamic state data, such as port status and statistics. The Monitor APIsupports requests for the following types of data:
l Port state and port statisticsl STP statel Trunk statel LACP statel LLDP statel Layer 2 MAC addressesl ACL countersl System status
List of Methods
The URL for the Monitor API has the following format:
https://<switch_ip>/api/v2/monitor/<path>/[<parameters>]
Each method defines the parameter meaning. Generally, if you do not set the parameter, the method retrievesdata for all instances. Set the parameter value to retrieve the data for the specified instance.
The following table describes the HTTP methods and parameters that are defined for each method:
Path Parameter Comments
switch/port port_name Retrieves information about the specifiedport. This method is equivalent toCLI command diagnose switch physical-ports summary.If no port name is specified, retrieves theinformation for all ports.
switch/port-speed port_name
Retrieves the speed settings that aresupported on the specified physical-port.If no port name is specified, retrieves thespeed settings for all ports.
switch/port-statistics port_name Retrieves the SNMP rx/tx statistics for thespecified port.If no port name is specified, retrieves thestats for all ports.
14 FortiSwitchOSREST APIFortinet Technologies Inc.
Monitor API List of Methods
Path Parameter Comments
switch/stp-state instance_id (0-15)
Retrieves STP instance information,equivalent to CLI command diagnose stpinstance list.Set instance_id = 255 to return information forall instances.Provide no instance_id to return informationfor the default stp instance.
switch/trunk-state trunk_name Retrieves trunk information for the specifiedtrunk.If no trunk name is specified, retrieves theinformation for all trunks.
switch/loop-guard-state n/aRetrieves Loop-guard status, equivalent toCLI command diagnose loop-guardinstance status.
switch/acl-stats policy_id Retrieves ACL statistics, equivalent toCLI command get switch acl counters.If no policy id is specified, retrieves thestatistics for all ACLs.
switch/lldp-state port_nameEquivalent to CLI command get switch lldpneighbors-detailPort name is required.
switch/mac-address port_name, trunk_name, vlan_id
Retrieve the list of mac-addresses that havebeen learned by the switch.Do not specify port_name and trunk_name inthe same request. However, the othercombinations are supported.
system/status n/a Equivalent to CLI command get systemstatus
FortiSwitchOSREST APIFortinet Technologies Inc.
15
Python Examples Monitor API
Python Examples
The following snippets of Python code provide examples of how to use the Monitor API.
Basic setup (use this code for each example)The following example shows how to log in to the API, retrieve the CSRF token, and set the CSRF token in theclient header.These are basic actions that are required before invoking any methods on the API.
url_login="https://192.168.1.99/logincheck"client = requests.session()
#Login requestpayload = "username=admin&secretkey="r = client.post(url_login, data=payload, verify=False)apscookie=r.cookies
#csrf token updatefor cookie in client.cookies:
if cookie.name == 'ccsrftoken':csrftoken = cookie.value[1:-1] # token stored as a list
client.headers.update({'X-CSRFTOKEN': csrftoken})
Retrieve port stateThe following example shows how to retrieve port state for all of the ports:
url_monitor_port="https://10.105.4.16/api/v2/monitor/switch/port/"r = client.get(url_monitor_port, cookies=apscookie, verify=False)print r.text
The following example shows how to retrieve the state for port 20:
url_monitor_port="https://10.105.4.16/api/v2/monitor/switch/port/"payload = {'port_name':'port20'}r = client.get(url_monitor_port, params = payload, cookies=apscookie, verify=False)print r.text
Retrieve ACL statisticsThe following example shows how to retrieve all of the ACL statistics:
url_monitor_acl="https://192.168.1.99/api/v2/monitor/switch/acl-stats/"r = client.get(url_monitor_acl, cookies=apscookie, verify=False)print r.text
The following example shows how to retrieve the statistics for one member of the ACL collection (ACL 100 in thisexample):
url_monitor_acl="https://192.168.1.99/api/v2/monitor/switch/acl-stats/"
16 FortiSwitchOSREST APIFortinet Technologies Inc.
Monitor API Python Examples
payload = {'policy_id':'100'}r = client.get(url_monitor_acl, params = payload, cookies=apscookie, verify=False)print r.text
Retrieve loop-guard stateThe following example shows how to retrieve loop-guard state:
url_monitor_lpg="https://10.105.4.16/api/v2/monitor/switch/loop-guard-state/"r = client.get(url_monitor_lpg, cookies=apscookie, verify=False)print r.text
FortiSwitchOSREST APIFortinet Technologies Inc.
17
Copyright© 2015 Fortinet, Inc. All rights reserved. Fortinet®, FortiGate®, FortiCare® and FortiGuard®, and certain other marks are registered trademarks of Fortinet,Inc., in the U.S. and other jurisdictions, and other Fortinet names herein may also be registered and/or common law trademarks of Fortinet. All other product or companynames may be trademarks of their respective owners. Performance and other metrics contained herein were attained in internal lab tests under ideal conditions, andactual performance and other results may vary. Network variables, different network environments and other conditions may affect performance results. Nothing hereinrepresents any binding commitment by Fortinet, and Fortinet disclaims all warranties, whether express or implied, except to the extent Fortinet enters a binding writtencontract, signed by Fortinet’s General Counsel, with a purchaser that expressly warrants that the identified product will perform according to certain expressly-identifiedperformancemetrics and, in such event, only the specific performancemetrics expressly identified in such binding written contract shall be binding on Fortinet. Forabsolute clarity, any such warranty will be limited to performance in the same ideal conditions as in Fortinet’s internal lab tests. In no event does Fortinet make anycommitment related to future deliverables, features, or development, and circumstances may change such that any forward-looking statements herein are not accurate.Fortinet disclaims in full any covenants, representations,and guarantees pursuant hereto, whether express or implied. Fortinet reserves the right to change, modify,transfer, or otherwise revise this publication without notice, and themost current version of the publication shall be applicable.