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
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
1 thought on “Python API Using FASTAPI – For Network Engineers – Part I”