Python Connect with API

In this lesson, we’ll take a look at how we can use Python to communicate with an Application Programming Interface (API). An API is a software interface that allows applications to communicate with other applications. In our case, we are going to communicate with an API using Python.

We are going to use the Python requests module. With this module, you can send all sorts of HTTP requests. Let’s install it with PIP:

pip install requests

We’ll try different APIs so we can test different things:

  • API without authentication: the most simple API to work with, great to learn the basics.
  • API with query parameters: we can use this to send parameters to the API.
  • API with authentication: most APIs require authentication. I’ll show you an example of how to authenticate with an API.

API without Authentication

When you try to communicate with an API for the first time in Python, you want to make sure you try an API that is simple to understand and has decent documentation. If possible, the API shouldn’t have authentication so you don’t have to worry about authentication methods like tokens, API keys, OAuth, etc.

One such API is the Date Nager API. You can use this API to fetch public holidays for any country and year. It’s a simple API that doesn’t require authentication and has decent documentation.

Here is my sample code:

Let me explain the code above:

  • We use the requests module to send an HTTP GET request to:
    • https://date.nager.at/api/v2/PublicHolidays/2020/US.
  • The API responds with HTTP status code 200 when we are able to connect.
  • The API returns the requested data in JSON format. We format JSON to a Python dictionary and store it in variable “data”.
  • When the API can’t find the requested content, it returns an HTTP status code 404.
  • When the API returns any other HTTP status code, we know something went wrong.
  • We iterate our dictionary and print all keys with “name”.

Excellent. We now have a list of all US public holidays in 2020.

Query Parameters

Let’s move on with a slightly more advanced example. This time we use the Datamuse API. This API is a word-finding query engine. It lets you send queries to find words that match certain criteria. Not something we as network engineers probably need, but it’s a great way to test query parameters and Datamuse offers good documentation.

For example, let’s say I want to find words that rhyme with the word “network”. You can use the following URL for this:

https://api.datamuse.com/words?rel_rhy=network

Go ahead and open the link above in your web browser. The part in the URL after the ? is the query parameter.

Let’s see if we can communicate with this API in Python:

The code above is very similar to our first example. I use the requests module to send an HTTP GET request to the URL. The code above works, but we can improve it in a more pythonic way.

Pythonic means that you use code that follows the best practices for Python and use it the way it is intended to be used.

Let’s try something else. Here is my code:

In the code above, I separated the URL from the query parameter. We also use requests.get instead of requests.request now.

The output is exactly the same, but our code looks a bit cleaner because of the separate query parameter.

Instead of using the requests library, you could use some other module. For example, Datamuse also has a Python module. These modules usually use the requests module under the hood and abstract away some of the complexity.

Using modules has both pros and cons. The advantage of a module is that it’s usually quicker to build something. The disadvantage is that some modules might work today, but won’t be maintained in the future.

For example, if you want to communicate with the Twitter API you could build something from scratch or use a popular module. an example such as Tweety.

In the case of Tweety, this module has been out there for 8 years and is well maintained.  If you find a module and the last time someone worked on it was over two years ago, it might be better to skip it and use the requests library directly. You can still look at the code and use parts of the module as inspiration for your own code.

API Authentication

Let’s move on to the next example. How about an API that requires authentication? I won’t cover every possible authentication method, but I do have a nice example that is network related. How about we communicate with Cisco’s DNA Center API ? Cisco has a sandbox environment for DNA Center. You can communicate with their API without registration.

I kept my sample code as short as possible, no if/else or try/except blocks so we can focus completely on the authentication part. Here is the code:

Let me explain the code above:

  • We have two functions:
    • The get_token function authenticates with DNA Center:
      • We send an HTTP POST request which includes the username, password, and a header which specifies that we use the JSON format.
      • When the DNA Center API authenticates us successfully, the API returns a token that we need to use for any other requests.
      • We store the token in the “token” variable.
    • The get_data_from_dna_center function retrieves data from DNA Center:
      • We send an HTTP GET request which includes a header with our token.
      • The base URL for this API is HTTPS://sandboxdnac.cisco.com/api/v1
      • The “endpoint” defines the data that we want to retrieve.

Excellent. We get a list of network devices and their uptime.

When working with APIs, an IDE with a decent debugger is very useful.

Conclusion

You have now learned how to communicate with APIs using Python:

  • API without authentication.
  • API with query parameters.
  • API with authentication.

These examples help to understand the basics. However, you should always check the API documentation to learn how to communicate with the API. If you are lucky, they provide examples for Python or you can use a module so you don’t have to work with the requests module directly.

Another lesson you might enjoy is the Introduction to REST API lesson. In this lesson, I explain what a REST API is and how to communicate with a CSR1000v router using the REST API.

I hope you enjoyed this lesson. If you have any questions please leave a comment.


Forum Replies

  1. Do you have any experience with opendcim?
    I’m looking to update devices via python using APIs

    Can you give me any examples to do this?

    Thanks

  2. Hello Giovanni

    This lesson describes how to connect via Python using APIs:

    https://networklessons.com/python/python-connect-with-api

    Although it does not use openDCIM, it gives you an idea of the methodology used. If you want to specifically use openDCIM, there’s a lot of documentation out there from the very simple to the complex. A good place to start may be the following Getting Started info about openDCIM.

    If you would like to see openDCIM or any other feature or tool on the site, you can always make a suggestion at the Member Ideas page below:

    https://

    ... Continue reading in our forum

Ask a question or join the discussion by visiting our Community Forum