CREATING AN API
As seems to be the trend over the past few years, absolutely everything needs an API. This is no different with our Countdown program and the excellent FastAPI library makes it incredibly easy to create one. The FastAPI library and supporting web server can be installed by opening a terminal and entering the following:
$ pip install fastapi
$ pip install uvicorn[standard]
The documentation (see screenshot below) is created by the FastAPI library. The code below is used to register the endpoint to generate a random set of letters (see GitHub for a fuller example):
from fastapi import FastAPI from countdown import Countdown
a = Countdown() app = FastAPI()
@app.get(“/generate/{numLetters}”) def generateWord(numLetters): a.letterNumber = int(numLetters) a.genRandomLetters() return {“numLetters”: numLetters, “generatedLetters”: a.
generatedLetters}
In this code sample, we import libraries and create instances of each. We then decorate a function with one of the FastAPI decorators – this essentially adds functionality to the function we create. The function takes an argument, which contains the number of letters. We then use the Countdown class to set the number of letters and generate a random set. We then return information using Python dictionaries. Running the uvicorn web server allows this to be tested:
$ python3 -m uvicorn countdownAPI:app --reload
Now, open your web browser and navigate to http://localhost: 8000/generate/8 and you will see an eight-letter random string is generated and returned. This can then be extended to other methods as well.