DEV Community

Cover image for Day 45: Beginner FastAPI Series - Part 2
John Enad
John Enad

Posted on

Day 45: Beginner FastAPI Series - Part 2

It's time to add the routes I listed in Part 1 to our FastAPI application and associating them with functions. This is just the initial setup to keep this project moving forward and this is far from the final product. At this time, all these methods will simply return a string of text, but they will eventually be modified to perform specific actions on the 'Person' entity.

These routes should be appended to the main.py file in the app folder:

@app.get("/api/persons")
def get_persons():
    return "read persons list"

@app.post("/api/persons")
def create_person():
    return "create person item"

@app.get("/api/persons/{id}")
def get_person(id: int):
    return f"read persons item id: {id}"

@app.put("/api/persons/{id}")
def update_person(id: int):
    return f"update persons item id: {id}"

@app.delete("/api/persons/{id}")
def delete_person(id: int):
    return f"delete persons item id: {id}"
Enter fullscreen mode Exit fullscreen mode

Just in case the application isn't running here is how to run it:

uvicorn app.main:app --host localhost --port 8000 --reload

With these routes implemented, you can turn your browser to http://localhost:8000/api/persons. The application will then respond with the text "read persons list".

The dynamic routes will also work. Try visiting http://localhost:8000/api/persons/1. The number '1' at the end of the URL will be recognized as the person's ID. FastAPI's routing feature will match the URL with the specified route and will replace {id} with '1'.

One of the really cool features of FastAPI is its built-in support for OpenAPI and JSON Schema. What this means is that it will automatically generate API documentation. We don't need to manually create an API documentation!

To see this firsthand, just type http://localhost:8000/docs into your browser's address bar.

Image description

The interactive documentation that is displayed can be used to test all the routes in your application. Just expand 'GET /api/persons' and click the 'Try it out' button. Then, click the blue 'Execute' button to call the get_persons method, just like you would from the browser.

I know I'm moving a little bit slower that I wanted but I also need to pace myself as there are other things I'm simultaneously studying at the moment (hint: 2 things and they both start with 'T').

Nevertheless, we have only scratched the surface but have already seen sparks of FastAPI's brilliance. I really like what I'm seeing and think FastAPI is coherent and well-structured.

The next installment of this series will go deeper into developing our 'Person' entity and making our methods work with it.

Note: In the next post, I will put the code in a public repo at Github

Top comments (0)