Programmatic Nautobot GraphQL Requests via Pynautobot
Tim Fiola
April 15, 2021
HomeBlogProgrammatic Nautobot GraphQL Requests via Pynautobot
Thanks to its ability to efficiently allow the request of specific information that can span multiple resources, GraphQL is a powerful query tool. A single GraphQL API request can return information that would otherwise require literally dozens of individual REST queries and extensive data filtering, post-processing, and isolation.
A prior blog post in this series covered how to craft Nautobot GraphQL queries using the Nautobot GraphiQL interface. Recall that the GraphiQL interface is just for testing the GraphQL queries. This post will build on that knowledge, showing you how to leverage those queries to craft remote GraphQL requests for programmatic use via the open source pynautobot Python library. The pynautobot project page is here; the GitHub repository can be found here.
The pynautobot Python library is an API wrapper that allows easy interactions with Nautobot. This specific article will focus the GraphQL capabilities within the library.
The examples in this post all use the public Nautobot demo site https://demo.nautobot.com/. Readers are encouraged to follow along.
Authentication
Security tokens are typically required for programmatic access to Nautobot’s data. The following sections cover how to obtain a token and how to leverage it within Postman to craft GraphQL API calls.
Tokens
Nautobot security tokens are created in the Web UI. To view your token(s), navigate to the API Tokens page under your user profile. If there is no token present, create one or get the necessary permissions to do so.
Getting Started with Pynautobot
Installing Pynautobot
pynautobot is a Python library. From your environment install it via pip3:
This first example will walk through a pynautobot GraphQL query in a Python interpreter.
Start a Python shell and import pynautobot:
% python3Python 3.9.2 (v3.9.2:1a79785e3e, Feb 192021,09:06:10) [Clang 6.0 (clang-600.0.57)] on darwinType "help","copyright","credits" or "license" for more information.>>>>>>>>>import pynautobot>>>
Taking a quick look at Classes within pynautobot, api is the one we will want to use. The help tells us that the api Class can take url and token as parameters.
This live example will use a query from a previous post. Define query in Python using the exact text from the query used in example 3 in the GraphiQL post:
NOTE: the query text can be found in the last section of the blog, under Text Query Examples and Results
>>>dir(nb.graphql)['__class__',<< dunders snipped >>,'api','query','url']>>>>>>help(nb.graphql.query)Help on method query inmodulepynautobot.core.graphql:query(query: str, variables: Optional[Dict[str, Any]] = None) -> pynautobot.core.graphql.GraphQLRecordmethodofpynautobot.core.graphql.GraphQLQueryinstanceRunsqueryagainstNautobotGraphqlendpoint.Args:query (str): Query string to send to the APIvariables (dict): Dictionary of variables to use with the query string, defaults to NoneRaises:GraphQLException:- When the query string is invalid.TypeError:- When `query` passed in is not oftypestring. - When `variables` passed in is not a dictionary. Exception: - When unknown error is passed in, please open an issue so this can be addressed.Examples:>>>try:... response.raise_for_status()... except Exception ase:... variable = e...>>> variable>>> variable.response.json(){'errors': [{'message':'Cannot query field "nae" on type "DeviceType". Did you mean "name" or "face"?','locations': [{'line':4,'column':5}]}]}>>> variable.response.status_code400Returns:GraphQLRecord: Response of the API call
Using the structure above, create the query and explore the results.
This next example features a full script, using an example from the GraphQL Aliasing with Nautobot post in this series. You can also see the YouTube video that accompanies the post here.
The script below features a query that uses GraphQL aliasing to request device names for multiple sites in a single query. The device names in each site will be returned grouped by the site name; each device name will be alaised with an inventory_hostname key (instead of name) for use in an Ansible environment.
The query text for this script was pulled directly from the Aliasing Solves the Problem section of the referenced blog post and copied directly into the query variable.
import jsonimport pynautobotfrom pprint import pprintprint("Querying Nautobot via pynautobot.")print()url = "https://demo.nautobot.com"print("url is: {}".format(url))print()query = """query { ams_devices:devices(site:"ams") {inventory_hostname:name} sin_devices:devices(site:"sin") {inventory_hostname:name} bkk_devices:devices(site:"bkk") {inventory_hostname:name}}"""print("query is:")print(query)print()token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"nb = pynautobot.api(url, token)response = nb.graphql.query(query=query)response_data = response.jsonprint("Here is the response data in json:")pprint(response_data)print()print("Here are the bkk devices:")pprint(response_data['data']['bkk_devices'])
Here is the script’s output:
% python3 -i graphql_ams_query_pynautobot.pyQuerying Nautobot via pynautobot.url is:https://demo.nautobot.comquery is:query {ams_devices:devices(site:"ams") {inventory_hostname:name}sin_devices:devices(site:"sin") {inventory_hostname:name}bkk_devices:devices(site:"bkk") {inventory_hostname:name}}Here is the response data injson:{'data': {'ams_devices': [{'inventory_hostname':'ams-edge-01'},{'inventory_hostname':'ams-edge-02'},{'inventory_hostname':'ams-leaf-01'},{'inventory_hostname':'ams-leaf-02'},{'inventory_hostname':'ams-leaf-03'},{'inventory_hostname':'ams-leaf-04'},{'inventory_hostname':'ams-leaf-05'},{'inventory_hostname':'ams-leaf-06'},{'inventory_hostname':'ams-leaf-07'},{'inventory_hostname':'ams-leaf-08'}],'bkk_devices': [{'inventory_hostname':'bkk-edge-01'},{'inventory_hostname':'bkk-edge-02'},{'inventory_hostname':'bkk-leaf-01'},{'inventory_hostname':'bkk-leaf-02'},{'inventory_hostname':'bkk-leaf-03'},{'inventory_hostname':'bkk-leaf-04'},{'inventory_hostname':'bkk-leaf-05'},{'inventory_hostname':'bkk-leaf-06'},{'inventory_hostname':'bkk-leaf-07'},{'inventory_hostname':'bkk-leaf-08'}],'sin_devices': [{'inventory_hostname':'sin-edge-01'},{'inventory_hostname':'sin-edge-02'},{'inventory_hostname':'sin-leaf-01'},{'inventory_hostname':'sin-leaf-02'},{'inventory_hostname':'sin-leaf-03'},{'inventory_hostname':'sin-leaf-04'},{'inventory_hostname':'sin-leaf-05'},{'inventory_hostname':'sin-leaf-06'},{'inventory_hostname':'sin-leaf-07'},{'inventory_hostname':'sin-leaf-08'}]}}Here are the bkk devices:[{'inventory_hostname':'bkk-edge-01'},{'inventory_hostname':'bkk-edge-02'},{'inventory_hostname':'bkk-leaf-01'},{'inventory_hostname':'bkk-leaf-02'},{'inventory_hostname':'bkk-leaf-03'},{'inventory_hostname':'bkk-leaf-04'},{'inventory_hostname':'bkk-leaf-05'},{'inventory_hostname':'bkk-leaf-06'},{'inventory_hostname':'bkk-leaf-07'},{'inventory_hostname':'bkk-leaf-08'}]>>>
Conclusion
To fully leverage GraphQL’s efficiency, it must be used programmatically. The first post in this series demonstrated using Nautobot’s GraphiQL interface to craft GraphQL queries. This post builds on that by showing how to convert those GraphQL queries into remote requests in Python code for programmatic use.
To find out more about pynautobot, including the additional capabilities not described in this post, start with the pynautobot Github repo.
Does this all sound amazing? Want to know more about how Network to Code can help you do this, reach out to our sales team. If you want to help make this a reality for our clients, check out our careers page.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. In case of sale of your personal information, you may opt out by using the link Do not sell my personal information. Privacy | Cookies
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
__hssc
30 minutes
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.
__hssrc
session
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.
cookielawinfo-checkbox-advertisement
1 year
Set by the GDPR Cookie Consent plugin, this cookie records the user consent for the cookies in the "Advertisement" category.
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
CookieLawInfoConsent
1 year
CookieYes sets this cookie to record the default button state of the corresponding category and the status of CCPA. It works only in coordination with the primary cookie.
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Cookie
Duration
Description
__cf_bm
30 minutes
Cloudflare set the cookie to support Cloudflare Bot Management.
li_gc
5 months 27 days
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.
lidc
1 day
LinkedIn sets the lidc cookie to facilitate data center selection.
UserMatchHistory
1 month
LinkedIn sets this cookie for LinkedIn Ads ID syncing.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Cookie
Duration
Description
__hstc
5 months 27 days
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).
_ga
1 year 1 month 4 days
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.
_gat_gtag_UA_*
1 minute
Google Analytics sets this cookie to store a unique user ID.
_gid
1 day
Google Analytics sets this cookie to store information on how visitors use a website while also creating an analytics report of the website's performance. Some of the collected data includes the number of visitors, their source, and the pages they visit anonymously.
AnalyticsSyncHistory
1 month
Linkedin set this cookie to store information about the time a sync took place with the lms_analytics cookie.
CONSENT
2 years
YouTube sets this cookie via embedded YouTube videos and registers anonymous statistical data.
hubspotutk
5 months 27 days
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.
ln_or
1 day
Linkedin sets this cookie to registers statistical data on users' behaviour on the website for internal analytics.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Cookie
Duration
Description
bcookie
1 year
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.
bscookie
1 year
LinkedIn sets this cookie to store performed actions on the website.
li_sugr
3 months
LinkedIn sets this cookie to collect user behaviour data to optimise the website and make advertisements on the website more relevant.
VISITOR_INFO1_LIVE
5 months 27 days
YouTube sets this cookie to measure bandwidth, determining whether the user gets the new or old player interface.
YSC
session
Youtube sets this cookie to track the views of embedded videos on Youtube pages.
yt-remote-connected-devices
never
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
yt-remote-device-id
never
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
yt.innertube::nextId
never
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.
yt.innertube::requests
never
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.