Python API client library for phpIPAM installations

Overview

phpypam: Python API client library for phpIPAM installation

PyPI version Codacy Badge Documentation Status

As we started to develop phpipam-ansible-modules we used an existing python library for phpIPAM API. As we needed a good error handling and we don't expect a quick fix of existing project we started to develop our own library.

installation

This library is hosted on pypi.org, so you can simply use pip to install it.

pip install phpypam

Alternatively you can install it from source. You need to do the following:

$ git clone https://github.com/codeaffen/phpypam.git
Cloning into 'phpypam'...
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 366 (delta 0), reused 0 (delta 0), pack-reused 365
Receiving objects: 100% (366/366), 88.57 KiB | 521.00 KiB/s, done.
Resolving deltas: 100% (187/187), done.
$ cd phpypam/
$ python setup.py install

quick start

To start using phpypam you simply have to write some lines of code.

import phpypam

pi = phpypam.api(
  url='https://ipam.example.com',
  app_id='ansible',
  username='apiuser',
  password='apiP455wd',
  ssl_verify=True
)
pi.get_entity(controller='sections')

making api connection

To connect to phpIPAM API you need some parameters to authenticate against the phpIPAM instance.

Parameter Description Default
url The URL to a phpIPAM instance. It includes the protocol (http or https).
app_id The app_id which is used for the API operations.
username The username which is used to connect to API. None
password The password to authenticate username against API. None
ssl_verify Should certificate of endpoint verified or not. Useful if you use a self signed certificate. True

Example connect to api and request current token:

connection_params = dict(
url='https://ipam.example.com',
  app_id='ansible',
  username='apiuser',
  password='apiP455wd',
  ssl_verify=True
)

pi = phpypam.api(**connection_params)

token = pi.get_token()

First of all you create a dictionary with the connection data. This dictionary will unpacked for creating a phpypam.api object.

If all went well you can use the get_token to get the currently valid token from API.

get available controllers

To work with the phpIPAM api it is useful if you know all available controllers. To achieve this you can either read the api documentation or you can use the controllers method.

controllers = pi.controllers()

The method returns a set with all supported controllers.

get an entity

To get an entity the get_entity method has to be used.

get_entity(controller, controller_path=None, params=None)

Example get a section by name:

entity = pi.get_entity(controller='sections', controller_path='foobar')

This call returns a dictionary for the entity with the name foobar.

create an entity

To create an entity the create_entity method has to be used.

create_entity(controller, controller_path=None, data=None, params=None)

Example create a section if it does not exists:

my_section = dict(
    name='foobar',
    description='new section',
    permissions='{"3":"1","2":"2"}'
)

try:
    entity = pi.get_entity(controller='sections', controller_path=my_section['name'])
except PHPyPAMEntityNotFoundException:
    print('create entity')
    entity = pi.create_entity(controller='sections', data=my_section)

In this example first we check if the section we work on already exists. If the PHPyPAMEntityNotFoundException is raised we create the entity.

update an entity

To update an entity you have to use the update_entity method.

update_entity(controller, controller_path=None, data=None, params=None)

Example update a section if it exists:

my_section['description'] = 'new description'

entity = pi.get_entity(controller='sections', controller_path=my_section['name'])
pi.update_entity(controller='sections', controller_path=entity['id'], data=my_section)

To change data you have to modify the value of the desired key to the value you want. You can see the data is changed in the dict from the former example. Then you get the entity to obtain its id to work on.

Note: All modifying operations need the id of an entity not the name.

In the last step you call update_entity and put the entity id in parameter controller_path with the data parameter you provide the fully entity description dictionary.

delete an entity

To delete an entity you have to use the delete_entity method.

delete_entity(controller, controller_path, params=None)

Example delete a existing section:

entity = pi.get_entity(controller='sections', controller_path=my_section['name'])
pi.delete_entity(controller='sections', controller_path=entity['id'])

In this example you request the entity you had created/updated in the above examples. After that you call delete_entity with the entity id from the request before.

possible exceptions

  • PHPyPAMInvalidCredentials - will be raised if something goes wrong with the authentication
  • PHPyPAMEntityNotFoundException - will be raised if an entity does not exists
  • PHPyPAMInvalidSyntax - will be raised for requests which will be answered with status code 400 from API
  • PHPyPAMException - for any errors which we catch but no specific exception exists this exception wil be raised
Comments
  • unable to login with no clear error message.

    unable to login with no clear error message.

    Hello,

    I m trying to test phpypam with the sample provide.

    pi = phpypam.api( url='http://myipam.com', app_id='xx', token='xxxxx', username='xxx', password='xxx', ssl_verify=False ) pi.get_entity(controller='sections')

    And i got the following error

    Traceback (most recent call last): File "test_ipam.py", line 10, in ssl_verify=False File "/lib/python3.6/site-packages/phpypam/core/api.py", line 66, in init self._login() File "/lib/python3.6/site-packages/phpypam/core/api.py", line 131, in _login resp = self._query(method=POST, auth=_auth) File "/lib/python3.6/site-packages/phpypam/core/api.py", line 121, in _query raise PHPyPAMException(code=result['code'], message=result['message']) phpypam.core.exceptions.PHPyPAMException

    Versions:

    • python 3.6.0
    • phpypam
    bug documentation 
    opened by kevinhuy 8
  • Added not-found error message for hostname search

    Added not-found error message for hostname search

    The following call raises a PHPyPAMException.

    pi.get_entity(controller='addresses', controller_path=f"search_hostname/{hostname}/")
    

    I would expect the library to raise PHPyPAMEntityNotFoundException instead. This PR fixes this by adding the error returned from phpipam to the expected list.

    opened by mattiasa 5
  • Unable to authenticate to API

    Unable to authenticate to API "Please provide token"

    Describe the bug This follows on from https://github.com/codeaffen/phpipam-ansible-modules/discussions/52

    Running the phpypam module on phpIPAM version 1.4.0 results in an unhandled error. Further debugging shows a HTTP 403 forbidden error with "Please provide token" from phpIPAM.

    To Reproduce Example code:

    import phpypam
    
    pi = phpypam.api(
      url='https://phpipam.server/',
      app_id='myappid',
      username='myusername',
      password='mypassword',
      ssl_verify=False
    )
    print(pi.get_entity(controller='sections'))
    

    Version 1.40 of phpIPAM used

    Expected behavior With the above code, I expect an output of the configured sections in phpIPAM

    Versions:

    • phpIPAM 1.4.0
    • phpypam 1.0.1

    Additional context Amending api.py in the core package as follows fixes the problem:

    72c72
    <     def _query(self, path='user/', headers=None, method=GET, data=None, params=None, auth=None, token=None):
    ---
    >     def _query(self, path='user', headers=None, method=GET, data=None, params=None, auth=None, token=None):
    

    It appears that from phpIPAM 1.4.1 and above, the trailing "/" is no longer needed. I tested there and it works fine without the trailing "/"

    I'm not sure if the above "fix" is the best way to fix the problem. If it is, let me know and I will try creating a pull request for that together with a feature enhancement for undefined errors (display the HTTP error and message).

    bug wontfix 
    opened by sidhoah8 5
  • Subnet address search with zero results raises incorrect exception

    Subnet address search with zero results raises incorrect exception

    Describe the bug When searching for addresses in an empty subnet a generic PHPyPAMException is raised instead of PHPyPAMEntityNotFoundException.

    To Reproduce Steps to reproduce the behavior:

    1. In phpIPAM, create a new subnet with no address entries.
    2. Search the subnet for addresses via phpypam: IPAM_API.get_entity(controller='subnets', controller_path=subnet['id']+'/addresses/')
    3. PHPyPAMException is raised with message "No addresses found"

    Expected behavior PHPyPAMEntityNotFoundException should be raised instead.

    Versions:

    • python: 3.8.10
    • phpypam: 1.0.2

    Additional context None.

    bug good first issue 
    opened by alexbb 3
  • fix #51 - wrong Exception on search on empty subnet

    fix #51 - wrong Exception on search on empty subnet

    • Fix #51 - When searching for addresses in an empty subnet
    • extend script to setup local test env to use podman if available
    • add make target to setup local phpipam test env with one command
    bug enhancement 
    opened by cmeissner 1
  • Initial Update

    Initial Update

    The bot created this issue to inform you that pyup.io has been set up on this repo. Once you have closed it, the bot will open pull requests for updates as soon as they are available.

    opened by pyup-bot 1
  • Bugfix: fix local test environment

    Bugfix: fix local test environment

    As most distributions switch from docker to podman we adapt our local test environment to make use of podman. We also make more data in for setting up the local test environment variable.

    opened by cmeissner 0
  • feat: enable matrix tests

    feat: enable matrix tests

    As phpipam-action now support different phpipam versions we switch all tests to matrix builds. So we can test different combinations of phpipam and python versions.

    opened by cmeissner 0
  • Switch test to containerized services

    Switch test to containerized services

    Like in codeaffen/phpipam-ansible-modules we want to run tests agains phpipam installation with containerized services here too. So we adapt the solution from there and switch our CI workflow to that approach For that we have to add ssl_verify to connection params and set default in Makefile

    opened by cmeissner 0
  • Search for non-existing hostname results not in correct exception

    Search for non-existing hostname results not in correct exception

    Describe the bug

    Look up for a non existing call raises a PHPyPAMException not PHPyPAMEntityNotFoundException.

    To Reproduce Steps to reproduce the behavior:

    pi.get_entity(controller='addresses', controller_path=f"search_hostname/{hostname}/")

    Expected behavior

    PHPyPAMEntityNotFoundException should be raised instead.

    Versions:

    phpypam <= 1.0.1

    Additional context

    bug 
    opened by cmeissner 0
  • provide pytests

    provide pytests

    • Add modules needed for recording and replaying
    • Record tests for replay in CI
    • Add CI workflow
    • create a valid server.xml before running tests
    • Add phpypam.api as fixture for most tests
    • remove unused imports
    opened by cmeissner 0
  • add a headers arg to create_entity()

    add a headers arg to create_entity()

    Hi, Thank you for this nice wrapper.

    Describe the bug Sometimes I run into this error https://github.com/phpipam/phpipam/issues/3177 and as stated in this issue, I have to pass {"content-type: "application/x-www-form-urlencoded"} in the headers to solve it. Currently create_entity() does not have a 'headers' argument, so I have to call _query() directly to pass the header to the request.

    Expected behavior It is a bite dirty to have to call an internal function directly, so I would like to be able to pass an 'headers' arg to create_entity(), and also to update_entity() and delete_entity for consistency I guess.

    Versions:

    • python 3.10
    • phpypam 1.0.2
    enhancement help wanted 
    opened by positiveEV 2
Releases(v1.0.2)
A Pythonic wrapper for the Wikipedia API

Wikipedia Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia. Search Wikipedia, get article summaries, get data

Jonathan Goldsmith 2.5k Dec 28, 2022
Isobot is originally made by notsniped. This is a remix of iso.bot by archisha.

iso6.9-08122021b-1.2beta Isobot is originally made by notsniped#0002. This is a remix of iso.bot by αrchιshα#5518. isobot6.9 is a Discord bot written

Kamilla Youver 3 Jan 11, 2022
IMDb + Auto + Unlimited Filter BoT

Telegram Movie Bot Features Auto Filter Manuel Filter IMDB Admin Commands Broadcast Index IMDB search Inline Search Random pics ids and User info Stat

Jos Projects 82 Dec 27, 2022
Asynchronous Python Wrapper for the Ufile API

Ufile.io Asynchronous Python Wrapper for the Ufile API (Unofficial).

Gautam Kumar 16 Aug 31, 2022
Dados Públicos de CNPJ disponibilizados pela Receita Federal do Brasil

Dados Públicos CNPJ Fonte oficial da Receita Federal do Brasil, aqui. Layout dos arquivos, aqui. A Receita Federal do Brasil disponibiliza bases com o

Aphonso Henrique do Amaral Rafael 102 Dec 28, 2022
pylunasvg - Python bindings for lunasvg

pylunasvg - Python bindings for lunasvg Pylunasvg is a simple wrapper around lunasvg that uses pybind11 to create python bindings. All public API of t

Eren 6 Jan 05, 2023
GitHub Usage Report

github-analytics from github_analytics import analyze pr_analysis = analyze.PRAnalyzer( "organization/repo", "organization", "team-name",

Shrivu Shankar 1 Oct 26, 2021
You can share your Chegg account for answers using this bot with your friends without getting your account blocked/flagged

Chegg-Answer-Bot You can share your Chegg account for answers using this bot with your friends without getting your account blocked/flagged Reuirement

Ammey Saini 27 Dec 24, 2022
The Encoder Bot For Python

The_Encoder_Bot Configuration Add values in environment variables or add them in config.env.example and rename file to config.env. Basics API_ID - Get

8 Jan 01, 2022
A Discord webhook spammer made in Python.

A Python made Discord webhook spammer usually used for token loggers to spam them/delete them original by cattyn I only made it so u can change the avatar to whatever u want instead of it being hardc

notperry1234567890 15 Dec 15, 2021
OliviaV2: danger bot with python

🎶 OLIVIA V2 🎵 Requirements 📝 FFmpeg NodeJS nodesource.com Python 3.7 or higher PyTgCalls 🧪 Get SESSION_NAME from below: Pyrogram 🎖 History Featur

Alvaro Einstein 2 Nov 04, 2021
Wrapper for Between - 비트윈을 위한 파이썬 라이브러리

PyBetween Wrapper for Between - 비트윈을 위한 파이썬 라이브러리 Legal Disclaimer 오직 교육적 목적으로만 사용할수 있으며, 비트윈은 VCNC의 자산입니다. 악의적 공격에 이용할시 처벌 받을수 있습니다. 사용에 따른 책임은 사용자가

1 Mar 15, 2022
Asyncio SDK for Azure Cosmos DB

Asyncio SDK for Azure Cosmos DB. This library is intended to be a very thin asyncio wrapper around the Azure Comsos DB Rest API. It is not intended to have feature parity with the Microsoft Azure SDK

Grant McDonald 4 Dec 04, 2021
A simple language translator with python and google translate api

Language translator with python A simple language translator with python and google translate api Install pip and python 3.9. All the required depende

0 Nov 11, 2021
A solution designed to extract, transform and load Chicago crime data from an RDS instance to other services in AWS.

This project is intended to implement a solution designed to extract, transform and load Chicago crime data from an RDS instance to other services in AWS.

Yesaswi Avula 1 Feb 04, 2022
Python client for Vektonn

Python client for Vektonn Installation Install the latest version: $ pip install vektonn Install specific version: $ pip install vektonn==1.2.3 Upgrad

Vektonn 16 Dec 09, 2022
A Advanced Auto Filter Bot Which Can Be Used In Many Groups With Multiple Channel Support....

Adv Auto Filter Bot This Just A Simple Hand Auto Filter Bot For Searching Files From Channel... Just Sent Any Text I Will Search In All Connected Chat

Albert Einstein 33 Oct 21, 2022
Date Time Userbot With Python

DATE_TIME_USERBOT An Telegram Bot By @Pythone_3 Config Vars API_ID : Telegram API_ID, get it from my.telegram.org/apps API_HASH : Telegram API_ID, get

Sinzz-sinan-m 2 Oct 20, 2021
An analysis of the efficiency of the COVID-19 vaccine

VaccineEfficiency 💉 An analysis of the efficiency of the COVID-19 vaccine 3 Methods 1️⃣ Compare country's vaccination data to number of day- to-day c

Stephanie Younes 1 Dec 10, 2021
EC2 that automatically move files received through FTP to S3

ftp-ec2-s3-cf EC2 that automatically move files received through FTP to S3 Installation CloudFormation template Deploy now! Usage IP / domain name: ta

Javier Santana 1 Jun 19, 2021