Create a Post
cancel
Showing results for 
Search instead for 
Did you mean: 
Erin_Horning
Explorer

Make API request using Python: issue with headers

I am trying to make a request to the checkpoint api using the function below, but when I invoke the function, I get the response: {\n  \"code\" : \"generic_err_missing_required_header\",\n  \"message\" : \"Missing header: [X-chkp-sid]\"\n}"

The headers are defined though and look right based on the documentation I have seen. What am I doing wrong here?

def get_tag_uid(sid):
      url = 'https://<some ip>/web_api/show-objects'

      headers = {
            'X-chkp-sid': sid,
            'Content-Type': 'application/json'
      }

      data = {
            'type': 'tag'
      }

      s = requests.session()

      response = s.post(url,headers,data,verify=False)

      return response.content

0 Kudos
13 Replies
Robert_Decker
Advisor

Hi,

We already have a Python SDK for our Management API - 

https://community.checkpoint.com/docs/DOC-1091

You can use it for any task. Its source code is public on GitHub repo...

Robert.

0 Kudos
Charles_Currier
Employee Alumnus
Employee Alumnus

First you need to perform a login.

The response will return the session ID which is required in the post for the call you have.

Here is an example:

import requests, json

def api_call(ip_addr, port, command, json_payload, sid):
    url = 'https://' + ap_addr + ':' + port + '/web_api/' + command
    if sid == '':
        request_headers = {'Content-Type' : 'application/json'}
    else:
        request_headers = {'Content-Type' : 'application/json', 'X-chkp-sid' : sid}
    r = requests.post(url,data=json.dumps(json_payload), headers=request_headers)
    return r.json()


def login(user,password):
    payload = {'user':user, 'password' : password}
    response = api_call('<some ip>', 443, 'login',payload, '')
    return response["sid"]

def get_tag_uid(sid):
    payload = {'type':'tag'}
    response = api_call('<some ip>', 443, 'show-objects', payload, sid)
    return response["sid"]

sid = login('my_username','secret')
print("session id: " + sid)

get_tag = get_tag_uid(sid)
print("tag UID: " + get_tag)

logout_result = api_call('<some ip>', 443,"logout", {},sid)
print("logout result: " + json.dumps(logout_result))‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I would add an additional filter for a specific object to make the work more efficiently.

This should simply dump all object tags.

Hope that helps.

Robert_Decker
Advisor

Hi,

I strongly recommend using our Python SDK.

Your example returns only first 50 tags, not all tags in database.

Robert.

0 Kudos
Nicholas_Sherid
Contributor

Hi Charles,

Nice clear easy to read code - I am brazenly ripping you off right now LOL Smiley Happy

cheers

Charles_Currier
Employee Alumnus
Employee Alumnus

True, calls to the API have a limit on the number of objects returned (50) so additional code to iterate through the list is necessary. However the Python SDK has its issues also and for the purpose of "learning" the API it is most appropriate to respond to the question and help others understand the API not just pull out another tool.
I hope that helped.

Robert_Decker
Advisor

There is nothing bad in learning API. In the contrary - I provided a link to this "another tool" source code, so anyone can read and learn from our experience.

0 Kudos
Erin_Horning
Explorer

Thanks everyone for the suggestions. A bit more context about what I am doing here: I am writing an ansible module that takes in a session id, an ip (for the management host), a list of tags and an object type, and outputs a list of names of any checkpoint objects whose tags match the inputted tags.

I got the module working, however what the module does is it currently returns all tags (limit the maximum of 500 although it is unlikely that this will every be reached) then filters the tags to find tags with a given name, then finds the objects whose tags match those tags. If there is a way to filter the tags returned in that initial call based on object type or the name of the tag, that would of course be much better both in terms of efficiency and in terms of avoiding the possibility of not returning all desired tags due to the object cap.

However, I am not sure if/how I could do this.The "filter" parameter of the show-objects API call appears to a require an ip as part of the filter but I cannot use an ip to filter tags. Any suggestions on how this could be done?

0 Kudos
Robert_Decker
Advisor

Here is a link for show-objects API command documentation - 

https://sc1.checkpoint.com/documents/latest/APIs/index.html#web/show-objects~v1.1

with examples, filters and so on.

Robert.

0 Kudos
Charles_Currier
Employee Alumnus
Employee Alumnus

If you haven't: Take a look at sk114661 Automate your management server using "Ansible"

and look at https://github.com/CheckPoint-APIs-Team/cpAnsible

and for filtering :

Name in:

{   "limit" : 10,   "offset" : 0,   "order" : [ {     "ASC" : "name"   } ],   "in" : [ "name", "ABC" ],   "type" : "object" }

Name not in:

{   "limit" : 10,   "offset" : 0,   "order" : [ {     "ASC" : "name"   }, {     "DESC" : "objId"   } ],   "not" : {     "in" : [ "name", "ABC" ]   },   "type" : "object" }

Perhaps try:

{   "limit" : 10,   "offset" : 0,   "order" : [ {     "ASC" : "name"   } ],   "in" : [ "tag", "ABC" ],   "type" : "object" }
0 Kudos
Nicholas_Sherid
Contributor

Charles Currier  total respect mate. BTW exactly how idempotent is ansible in practice when used against checkpoint?  This sounds awesome for my story of applying staging and test firewall playbooks.

BTW I found a typo in line 4 and hacked it about a bit, used a main function and removed the tag function for me(also being a bit naughty and disabling verification, yeah but I'm testing etc i ran with 2.7.15... omg when will the world move to v3?

Obviously argpass or somehting is better than static def's of uid and pw, sorry if obvious

import requests
import json

mgmt_username = 'some_username'
mgmt_password = 'some_password'
mgmt_server = 'some_mgmt_ipaddress'


def api_call(ip_addr, port, command, json_payload, sid):
    url = 'https://' + ip_addr + ':' + str(port) + '/web_api/' + command
    if sid == '':
        request_headers = {'Content-Type' : 'application/json'}
    else:
        request_headers = {'Content-Type' : 'application/json', 'X-chkp-sid' : sid}
    r = requests.post(url,data=json.dumps(json_payload), headers=request_headers, verify=False)
    return r.json()


def login(user,password):
    payload = {'user':user, 'password' : password}
    response = api_call(mgmt_server, 443, 'login',payload, '')
    return response["sid"]


def get_tag_uid(sid):
    payload = {'type':'tag'}
    response = api_call(mgmt_server, 443, 'show-objects', payload, sid)
    return response["sid"]


def main():
    sid = login(mgmt_username,mgmt_password)
    print("session id: " + sid)

    logout_result = api_call(mgmt_server, 443,"logout", {},sid)
    print("logout result: " + json.dumps(logout_result))


if __name__ == '__main__':
    main()
Charles_Currier
Employee Alumnus
Employee Alumnus

Aww man! 

Glad to be of assistance. Please let me know if I can be of help in the future and I would love to see the final result!

Thanks,

CB Currier

Volkan_KARABACA
Explorer

Hello Friends, I am trying to understand API Usage, I did whatever you write here but I am getting no result

My Python Code is same like you :

import requests
import json

from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

mgmt_username = 'admin'
mgmt_password = 'pass1234'
mgmt_server = '192.168.100.254'

def api_call(ip_addr, port, command, json_payload, sid):
url = 'https://' + ip_addr + ':' + str(port) + '/web_api/' + command
if sid == '':
request_headers = {'Content-Type' : 'application/json'}
else:
request_headers = {'Content-Type' : 'application/json', 'X-chkp-sid' : sid}
r = requests.post(url,data=json.dumps(json_payload), headers=request_headers, verify=False)
return r.json()


def login(user,password):
payload = {'user':user, 'password' : password}
response = api_call(mgmt_server, 443, 'login',payload, '')
return response["sid"]


def get_tag_uid(sid):
payload = {'type':'tag'}
response = api_call(mgmt_server, 443, 'show-objects', payload, sid)
return response["sid"]


def main():
sid = login(mgmt_username,mgmt_password)
print("session id: " + sid)

logout_result = api_call(mgmt_server, 443,"logout", {},sid)
print("logout result: " + json.dumps(logout_result))


if __name__ == '__main__':
main()

Resulst is ;

session id: _ujo0oCE9EMDdOctxCwGjImTJwuxA6sIQT8EYq0CB1s
logout result: {"message": "OK"}

I dont understand why is not displaying "show-objects"

Regards for help

0 Kudos
Joshua_Hatter
Employee
Employee

Your code is working as expected. You never call get_tag_uid in main, also get_tag_uid returns the incorrect value. Should probably only return response not response['sid'].

Leaderboard

Epsum factorial non deposit quid pro quo hic escorol.

Upcoming Events

    CheckMates Events