Shortly after I started at Snyk last year, I started experimenting with the Snyk API. I picked Python for those experiments, and ended up writing a nice client library, called pysnyk. I'm now going to try experiment by writing a series of posts about it. My intent is for these posts to be a mix of how-to and behind the scenes conversations. Snyk customers can do some interesting things with the API, and more generally API client design decisions are an interesting topic.
Let's start about with a very basic introduction:
Installation
Assuming you're already a Snyk customer and have the CLI installed, you can grab your token locally using:
snyk config get api
You can also find the token in the settings page in Snyk if you prefer.
pysnyk is available on PyPi, so installation is as simple as:
pip install pysnyk
If you're using other tools like Pipenv or Poetry then you can install in a similar way.
Instantiating the client
Most of the time you'll start by grabbing a SnykClient
:
import snyk
client = snyk.SnykClient("<your-api-token>")
You can choose to inject the token however you choose, but I typically use an environment variable called SNYK_TOKEN
which also works with the CLI and Snyk Docker images. In the simple case (without error checking):
import os
import snyk
token = os.environ["SNYK_TOKEN"]
client = snyk.SnykClient(token)
Managers
SnykClient
has a small number of methods as most operations in Snyk require a Snyk Organization as context. For that we can grab one via the organizations
manager.
>>> client.organizations
>>> <snyk.managers.OrganizationManager object at 0x1052d6e50>
>>> client.organizations.all()
>>> [Organization(name='Some Org', id='5fb978a0-aaas-bbbb-8af6-8888cccc8888', group=OrganizationGroup(name='Some Group', id='e9e44bd0-ddddd-44f3-eeeee-1111gggg2222')]
The manager here is a pattern used throughout the client. It's inspired by things like the Django QuerySet and provides a consistent Python API for accessing and manipulating the various objects returned by the Snyk API.
Hello world
To round out this first post, let's see a very simple example of using pysnyk. We'll create a script to loop over all of the organizations you have access to and print out the number of projects in each of them.
import os
import snyk
token = os.environ["SNYK_TOKEN"]
client = snyk.SnykClient(token)
for org in client.organizations.all():
projects = org.projects.all()
print(f"{org.name} has {len(projects)} projects")
When run, this should output something like:
Some Org has 8 projects
Some Other Org has 3 projects
We've just scratched the surface with this simple example. The Snyk API covers quite a bit of ground and the Python client covers the majority of the API. In future posts we'll hopefully delve into more examples, but in the meantime the above should get you started.
Top comments (1)
This library didn't bring any issue or vulnerability.