Testing with FastAPI
It is not that difficult to test an API. There are tools like postman that can do a lot for you. I do not use those tools for automated tests itself. I use them when I do some manual tests. For my automated tests, I use java or python. That is not the purpose of this post though.
Suppose that your team creates a new application to search for cat names. A simple API is created. We can fetch all cats and post new cat names.
The tests for that are created within minutes when using the request library written in python. The developers are not ready with implementing at the point.
Do we have good test code?
Can we check if our test code is correctly implemented?
It is possible with FastAPI. FastAPI is a web framework in Python. It can build APIs with python within seconds. It is very easy to use.
You can create a simple server with FastAPI that can mimick the SUT. Let’s create the simple API that our developers make. But of course we use some simple implementation. We do not connect to any database or other storage locations.
Our GET method can look like this:
from fastapi import FastAPI
app = FastAPI()
@app.get("/cats")
async def get_cats():
return {"cats": ["Minou", "Lixi"]}
And the put method to create new cats can look like this.
from fastapi import FastAPI
app = FastAPI()
cats = ["Minou", "Lixi"]
@app.get("/cats")
async def get_cats():
return {"cats": cats}
@app.post("/cats/")
async def create_cat(catname: str):
cats.append(catname)
return {"created": catname}
The server is started with following command
uvicorn mail:app --reload
The test code can now run against localhost on port 8000. That is the default.
That is not all. FastAPI creates also interactive API docs, like swagger. The documentation can be accessed on http://127.0.0.1:8000/docs
References
- More and better information can be found on the webpage of FastAPI.
- Photo by Marc-Olivier Jodoin on Unsplash