---
title: "API Programmability: Part 4: Diagramming"
id: "16704"
type: "post"
slug: "api-programmability-part-4-diagramming"
published_at: "2022-05-20T11:48:13+00:00"
modified_at: "2026-09-17T17:01:36+00:00"
url: "https://ipfabric.io/blog/api-programmability-part-4-diagramming/"
markdown_url: "https://ipfabric.io/blog/api-programmability-part-4-diagramming.md"
excerpt: "In Part 3, we discussed using the python-ipfabric SDK to interact with IP Fabric’s API – did you know that you can also use it to create diagrams using the API? Find a coding example on GitLab at 2022-05-20-api-programmability-part-4-diagramming. Blog..."
taxonomy_category:
  - "Discovery"
taxonomy_post_tag:
  - "Cloud visibility"
  - "Network visibility"
---

# API Programmability: Part 4: Diagramming

[https://ipfabric.io/author/ipf-team/](https://ipfabric.io/author/ipf-team/)
[IPF Team](https://ipfabric.io/author/ipf-team/)

Published

20 May 2022

Updated

17 Sep 2026

In [Part 3](https://ipfabric.io/blog/api-programmability-part-3-webhooks/)
, we discussed using the [python-ipfabric](https://pypi.org/project/ipfabric/)
 SDK to interact with IP Fabric’s API – did you know that you can also use it to create diagrams using the API?

Find a coding example on GitLab at [2022-05-20-api-programmability-part-4-diagramming](https://gitlab.com/ip-fabric/integrations/marketing-examples/-/tree/main/blogs/2022-05-20-api-programmability-part-4-diagramming)
.

**Blog post updated 2023-11-15 for ipfabric SDK version 6.5.0.**

## Requirements

- Python 3.8
- python-ipfabric
  - pip install “ipfabric>=6.5”

- IP Fabric version 6.4 or greater

## Diagram Methods

There are four options for returning data in the `Diagram` class.

- `IPFClient().diagram.png()`: Returns PNG image as a bytes string.
- `IPFClient().diagram.svg()`: Returns SVG image as a bytes string.
- `IPFClient().diagram.json()`: Returns the raw JSON from IP Fabric.
- `IPFClient().diagram.model()`: Takes the raw JSON and converts it into a python object with type hints.

Each of these methods has five input parameters, and only the first one is required:

- parameters (required): Python object of class Unicast, Multicast, Host2GW, or Network.
- snapshot_id: A snapshot ID to override the default when the class was initiated.
- overlay: Overlay object which specifies a comparison snapshot or intent rule overlay.
- graph_settings: Python object of NetworkSettings (Network parameter) or PathLookupSettings (Unicast, Multicast, or Host2GW parameter).
- unicast_swap_src_dst: Boolean that if set to True it will swap the Source and Destination IP, Ports, and Regions (only used with the Unicast parameter).

## Host to Gateway Path Lookup

This is the most basic diagram as it takes a single IP address. The imports will differ depending on the type of graph.

```
# 1_host2gateway.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Host2GW

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

# Get Random Host
    host = ipf.inventory.hosts.all(filters={"ip": ["cidr", "10.35.0.0/16"]})[3]['ip']

    with open(path.join('path_lookup', '1_host2gateway.png'), 'wb') as f:
        f.write(ipf.diagram.png(Host2GW(startingPoint=host)))
```

## Network Diagram Example

The Network class accepts 3 input parameters. If no parameters are defined, this will create a graph similar to going to the UI and *Diagrams > Network*.

- sites: String of a single `site name` or a List of `site names`.
- all_network: If set to True it will show all sites as clouds in the diagram and only expand the sites specified in the above parameter (default False).
- layouts: List of Layout objects to change the layout of a particular site.
  - Valid layouts: [“circular”, “downwardTree”, “hierarchical”, “radial”, “universal”, “upwardTree”]

```
# 2_network.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Network, Layout

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

    with open(path.join('network', '2_1_network.png'), 'wb') as f:
        f.write(ipf.diagram.png(Network(sites='MPLS', all_network=True)))

    with open(path.join('network', '2_2_network.png'), 'wb') as f:
        f.write(ipf.diagram.png(Network(sites=['LAB01', 'HWLAB'], all_network=False)))

    with open(path.join('network', '2_3_network.png'), 'wb') as f:
        f.write(ipf.diagram.png(
            Network(sites='L71', all_network=False, layouts=[Layout(path='L71', layout='upwardTree')])
        ))
```

### 2_1_network.png

### 2_2_network.png

### 2_3_network.png

## Diagram Overlay

Before moving on to Unicast and Multicast let’s take a look at how to overlay a snapshot comparison or specific intent rule onto your graph. You can apply this to any type of graph.

### Snapshot Comparison

```
# 3_network_overlay.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Network, Overlay

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

    with open(path.join('network', '3_1_network_snap_overlay.png'), 'wb') as f:
        f.write(ipf.diagram.png(Network(sites='MPLS', all_network=False),
                                    overlay=Overlay(snapshotToCompare='$prev')))
```

### Intent Rule

To overlay an Intent Rule you must first get the ID of the rule to submit. In this example, we are using the ipfabric package to load the intents and get a rule by name. Find more examples of extracting intent rule IDs [here](https://gitlab.com/ip-fabric/integrations/python-ipfabric/-/blob/develop/examples/intent.py)
.

```
# 3_network_overlay.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Network, Overlay

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

# Get intent rule ID
    ipf.intent.load_intent()
    intent_rule_id = ipf.intent.intent_by_name['NTP Reachable Sources'].intent_id

    with open(path.join('network', '3_2_network_intent_overlay.png'), 'wb') as f:
        f.write(ipf.diagram.png(Network(sites=['L71'], all_network=False),
                                overlay=Overlay(intentRuleId=intent_rule_id)))
```

## Unicast Path Lookup

The next two examples make it a bit clearer *why* we first create a python object and then pass it into the diagramming functions. The amount of options required are quite lengthy, and this keeps your code cleaner and provides great type hints (see below). Additionally, it has many built-in checks to ensure you provide the correct data before submitting the payload to IP Fabric and returning an error.

### ICMP Example

For all valid ICMP types please refer to [icmp.py](https://gitlab.com/ip-fabric/integrations/python-ipfabric-diagrams/-/blob/develop/ipfabric_diagrams/icmp.py)
.

```
# 5_unicast_path_lookup.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import icmp, Unicast

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

    unicast_icmp = Unicast(
        startingPoint='10.47.117.112',
        destinationPoint='10.66.123.117',
        protocol='icmp',
        icmp=icmp.ECHO_REQUEST,  # Dict is also valid: {'type': 0, 'code': 0}
        ttl=64,
        securedPath=False  # UI Option 'Security Rules'; True == 'Drop'; False == 'Continue'
    )

    with open(path.join('path_lookup', '5_1_unicast_icmp.png'), 'wb') as f:
        f.write(ipf.diagram.png(unicast_icmp))
```

### TCP or UDP Example

TCP and UDP accept `srcPorts` and `dstPorts` which can be a single port number, a comma-separated list, a range of ports separated by a `-`, or any combination of them. The `applications`, `srcRegions`, and `dstRegions` arguments are used for Zone Firewall rule checks and these default to any (`.*`).

```
# 5_unicast_path_lookup.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Unicast, OtherOptions

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

    unicast_tcp = Unicast(
        startingPoint='10.47.117.112',
        destinationPoint='10.66.123.117',
        protocol='tcp',
        srcPorts='1024,2048-4096',
        dstPorts='80,443',
        otherOptions=OtherOptions(applications='(web|http|https)', tracked=False),
        srcRegions='US',
        dstRegions='CZ',
        ttl=64,
        securedPath=False
    )

    with open(path.join('path_lookup', '5_2_unicast_tcp.png'), 'wb') as f:
        f.write(ipf.diagram.png(unicast_tcp))

    with open(path.join('path_lookup', '5_3_unicast_tcp_swap_src_dst.png'), 'wb') as f:
        f.write(ipf.diagram.png(unicast_tcp, unicast_swap_src_dst=True))

# Subnet Example
    unicast_subnet = Unicast(
        startingPoint='10.38.115.0/24',
        destinationPoint='10.66.126.0/24',
        protocol='tcp',
        srcPorts='1025',
        dstPorts='22',
        securedPath=False
    )

    with open(path.join('path_lookup', '5_4_unicast_subnet.png'), 'wb') as f:
        f.write(ipf.diagram.png(unicast_subnet))
```

#### Subnet Example:

### Entry Point Example

This is a new graphing feature in version 4.3 and above that allows you to specify a device and interface a packet enters your network. Perhaps you have a firewall rule to allow a certain IP address or subnet and want to verify that this is functioning correctly. The `sn` value is the IP Fabric unique serial number, `iface` is the `intName` or `Interface` column (not to be confused with `Original Name`), and the `hostname` is also required. The easiest way to collect this information is from the *Inventory > Interfaces* table. The `sn` is not a visible column in the UI, but is available from the API.

```
# Example pulling Interface Inventory table
from ipfabric import IPFClient
ipf = IPFClient(base_url='https://demo3.ipfabric.io/', token='token', verify=False)
interfaces = ipf.inventory.interfaces.all(columns=['sn', 'hostname', 'intName'])
```

```
# 5_unicast_path_lookup.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Unicast, Algorithm, EntryPoint

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

# User Defined Entry Point Example
    unicast_entry_point = Unicast(
        startingPoint='1.0.0.1',
        destinationPoint='10.66.126.0/24',
        protocol='tcp',
        srcPorts='1025',
        dstPorts='22',
        securedPath=True,
        firstHopAlgorithm=Algorithm(entryPoints=[
            EntryPoint(sn='test', iface='eth0', hostname='test'),
            dict(sn='test', iface='eth0', hostname='test')  # You can also use a dictionary
        ])
    )
```

## Multicast Path Lookup

Multicast is very similar to Unicast except some of the parameter names have changed. You can also specify a `receiver` IP address but this is optional.

```
# 7_multicast.py
from os import path

from ipfabric import IPFClient
from ipfabric.diagrams import Multicast

if __name__ == '__main__':
    ipf = IPFClient()  # IPFClient(base_url='https://demo3.ipfabric.io/', auth='token', verify=False, timeout=15)

    multicast = Multicast(
        source='10.33.230.2',
        group='233.1.1.1',
        receiver='10.33.244.200',
        protocol='tcp',
        srcPorts='1024,2048-4096',
        dstPorts='80,443',
    )

    with open(path.join('path_lookup', '7_multicast.png'), 'wb') as f:
        f.write(ipf.diagram.png(multicast))
```

## JSON and Model Outputs

One of the great advantages of using this package is returning a Python object instead of returning the raw JSON. This allows a user to more easily understand the complex textual data returned by IP Fabric that represents how the edges (links) connect to the nodes (devices, clouds, etc.) and the decisions a packet may take. You can accomplish this via the JSON output but returning an object provides type hints along with the ability to export the model as a JSON schema. Please note that the model is not the exact same as the JSON output and some structure has been changed for ease of use. It also dynamically links some internal objects to eliminate the need to do extra lookups and references.

```
# 6_json_vs_model.py
from ipfabric.diagrams.output_models.graph_result import GraphResult

if __name__ == '__main__':
    print(GraphResult.model_json_schema())
"""
{
  "title": "GraphResult",
  "type": "object",
  "properties": {
    "nodes": {
      "title": "Nodes",
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/Node"
      }
    },
    "edges": {
      "title": "Edges",
      "type": "object",
      "additionalProperties": {
        "anyOf": [
          {
            "$ref": "#/definitions/NetworkEdge"
          },
          {
            "$ref": "#/definitions/PathLookupEdge"
          }
        ]
      }
    },
...
"""
```

## Summary

The ability to create diagrams using the API allows for greater automation and integration into other applications. Many of our customers use this feature to create chatbots to speed up troubleshooting, as shown below. This example is from the [Network to Code](https://www.networktocode.com/)
 [nautobot-plugin-chatops](https://github.com/nautobot/nautobot-plugin-chatops)
 plugin.

Another useful feature is performing a Path Lookup and parsing the JSON output to ensure traffic is flowing apart of a review process. We have partnered with [Itential](https://www.itential.com/)
to demonstrate how using their low-code automation platform can automate ServiceNow requests and ensure that a newly deployed IP has access to correct network services during a Change Control review. Keep an eye out for a video of this exciting demonstration!

If you have any questions, comments, or bug requests please send an email to [[email protected]](/cdn-cgi/l/email-protection#4b213e383f222565212e2d2d2e39320b223b2d2a29392228652224)
 or [open an issue request on the GitLab repository](https://gitlab.com/ip-fabric/integrations/python-ipfabric/-/issues)
.

## Related Resources

Discovery

### [Network Labels 101: How to Enrich Your Network Discovery Data](https://ipfabric.io/blog/network-labels-101-how-to-enrich-network-discovery-data/)

Learn how to create and use labels to filter network discovery data, run intent checks, enforce RBAC policies, and more.

Discovery

### [Network Discovery 101: How to Build a Reliable Network Source of Truth](https://ipfabric.io/blog/network-discovery-build-network-source-of-truth/)

Embarking on an M&A? Building for AIOps? You need a reliable network source of truth—and that starts with network discovery.

Discovery

### [3 Ways to Improve Network Visibility in Hybrid Multi Cloud Environments](https://ipfabric.io/blog/ip-fabric-hybrid-multi-cloud-network-visibility/)

As your cloud footprint grows, it can be difficult to scale network visibility. Digital twin platforms like IP Fabric can unify insights across hybrid multi cloud environments, serving as a single source of truth.
