Skip to content

Network Automation

My journey with Network & Cloud Automation

Menu
  • Beginner
  • DevOps-NetDevOps
  • Network Automation
    • Docker
    • Python Libraries
      • NAPALM
      • Netmiko
      • Jinja2
      • Scrapli
      • Yang
  • Cloud Automation
    • Terraform
  • Python 🐍 Tips and Tricks
Menu
fastapi_1

Python API Using FASTAPI – For Network Engineers – Part I

Posted on November 1, 2021November 4, 2021 by Gurpreet Kochar

There are multiple frameworks one could leverage to write a simple API but in this post, we are going to talk about a relatively newer framework called FASTAPI for writing your own quick and simple python API using FASTAPI for network automation.

Step1:- Create a virtual environment and install the required libraries.

virtualenv fastapi
source fastapi/bin/activate
pip3 install fastapi
pip3 install pandas
pip3 install unicorn

Step2:- Download database.csv

databaseDownload

Step3:- Create a main.py in the same folder as database.csv and make sure the virtual environment is activated.

We are using pandas to load the csv file and convert csv to json

from fastapi import FastAPI
import json
import pandas as pd

app = FastAPI()

df = pd.read_csv('database.csv', sep='\t')
device_list = json.loads(df.to_json(orient='records'))
print(device_list)


[
    {'hostname': 'rtr-indi-ce01', 'device_category': 'router', 'model': 'ISR2821'},
    {'hostname': 'rtr-usam-ce01', 'device_category': 'router', 'model': 'ASR1001'},
    {'hostname': 'rtr-cana-ce01', 'device_category': 'router', 'model': 'ISR4321'},
    {'hostname': 'sw-indi-cs01', 'device_category': 'switch', 'model': 'WS-C3750'},
    {'hostname': 'sw-usam-cs01', 'device_category': 'switch', 'model': 'N7K-C7004'},
    {'hostname': 'sw-cana-cs01', 'device_category': 'switch', 'model': 'WS-C3850'}
]

Creating a GET API endpoint for retrieving all devices is now as simple as adding two more lines and starting the webserver

@app.get("/")
def get_routers():
    return {"devices": device_list}

To start the webserver, we type the below command in the CLI

uvicorn main:app --reload

main --> is the name of the file
app  --> is the name of the instance of the FastAPI() class you created in main.py

For example, if you saved your code in myapi.py and called the instance as fast_api_inst

from fastapi import FastAPI
import json
import pandas as pd

fast_api_app = FastAPI()

Execute the server by using
uvicorn myapi:fast_api_app --reload

There are a couple of ways we can launch the server and specify other launch options but for now we are keeping it simple and going with the documentation. Once the server is launched, go to http://127.0.0.1:8000/ as the default address to access the root endpoint of ‘/’

You could install a chrome extension called “JSON Formatter” to pretty-print the JSON output like shown below

That’s all we need to get up and running with the API. Assume we need to have separate endpoints for all device_types like routers and switches which could also be handled by using query parameters but for the sake of simplicity, let’s assume we need separate endpoints, and doing so is also as easy as

@app.get("/routers")
def get_routers():
    routers = [device for device in device_list if device['device_category'] == 'router']
    return {"routers": routers}

We are filtering the device_list for routers and returning the result when someone requests for “/routers”

and the same could be done for switches too

@app.get("/switches")
def get_switches():
    switches = [device for device in device_list if device['device_category'] == 'switch']
    return {"routers": switches}

Now, you may want this filtering to happen once, and then every time someone accesses the endpoints, the content is served directly from memory unlike in this case the routers and switches will be calculated every time that endpoint is requested. So we can take these operations outside the endpoint definitions.

from fastapi import FastAPI
import json
import pandas as pd
from rich import print

app = FastAPI()

df = pd.read_csv('database.csv', sep='\t')
device_list = json.loads(df.to_json(orient='records'))
routers = [device for device in device_list if device['device_category'] == 'router']
switches = [device for device in device_list if device['device_category'] == 'switch']

@app.get("/")
def get_routers():
    return {"devices": device_list}

@app.get("/routers")
def get_routers():
    return {"routers": routers}

@app.get("/switches")
def get_switches():
    return {"routers": switches}

There are many ways to achieve the same end result but for now, I want to keep it simple, get the basics right and build as we gradually learn more together. In part II of this series on Building Python API Using FASTAPI we will see how to use dynamic routes

Python API Using FASTAPI – For Network Engineers – Dynamic Routes – Part II

Know someone who may benefit? Share this:

  • Tweet
  • Click to share on Telegram (Opens in new window) Telegram
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to email a link to a friend (Opens in new window) Email
  • More
  • Click to print (Opens in new window) Print
  • Click to share on Reddit (Opens in new window) Reddit
  • Share on Tumblr
  • Pocket

Like this:

Like Loading...

Related

1 thought on “Python API Using FASTAPI – For Network Engineers – Part I”

  1. Pingback: Python API Using FASTAPI - For Network Engineers - Dynamic Routes - Part II –

Leave a ReplyCancel reply

All Blog Posts
My Resume

Upcoming Posts

Sorry - nothing planned yet!

Recent Posts

  • How to backup configuration to TFTP Server using Ansible – Part II
  • How to backup network devices using Ansible – Part I
  • Netmiko SSH Proxy/JumpServer
  • A short note on SASE
  • Understanding Ansible

Recent Comments

  1. Jack on Multithreading with Python for Network Engineers
  2. LifeCanvas on [Theory] Multithreading vs Multiprocessing vs AsyncIO
  3. Jasper Horng on Netmiko SSH Proxy/JumpServer
  4. asdfasdf on Python API Using FASTAPI – UPDATE – PUT – PATCH – Part V
  5. Gurpreet Kochar on Python Scrapli AsyncIO Usage

Archives

  • September 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
Topic Request / Suggestion
Loading
© 2025 Network Automation | Powered by Minimalist Blog WordPress Theme
 

Loading Comments...
 

    %d