Linux Format

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 documentat­ion (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 generateWo­rd(numLetters): a.letterNumb­er = int(numLetters) a.genRandomL­etters() return {“numLetters”: numLetters, “generatedL­etters”: a.

generatedL­etters}

In this code sample, we import libraries and create instances of each. We then decorate a function with one of the FastAPI decorators – this essentiall­y adds functional­ity 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 informatio­n using Python dictionari­es. Running the uvicorn web server allows this to be tested:

$ python3 -m uvicorn countdownA­PI: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.

 ?? ?? FastAPI uses swagger to generate documentat­ion from the Python code.
FastAPI uses swagger to generate documentat­ion from the Python code.

Newspapers in English

Newspapers from Australia