In Part 3 of this series, we have created a simple application based on FastAPI and added a database layer from models to repositories. Now, we will cover the below features as a part of this post.

  • Crud API on User Table using the models & repositories.
  • Generically handle API Exceptions.

The Part 4 implementation is available in the GitHub repository.

CRUD API on User Table using the models & repositories

We define all crud endpoints in the file api_user.py

All endpoints are registered in the router file router.py

This sub router has been registered to the FastAPI app in the main.py file.

#main.py #add below lines
app.include_router(router.api_router, prefix='/v1')

We have created a services package in the app. Then we add API specific service file. We have created a file user_service.py and added all the business logic inside this file.

We have created a schemas package in the app. All the API request & response contracts are defined here. We have created a user.py that will have all request & response structures for the /users endpoint.

Phew !!! We have completed the CRUD operations part.

Handle API Exceptions in a generic way.

All APIs should handle the error in a structured way.

  1. The error body has to be standardized.
  2. The response should have proper error codes

We provide a consistent API error response structure with status code, error code & error message across all APIs.

Add the RequestErrorHandler to main.py

@app.exception_handler(RequestError)
async def request_error_internal(request, exc):
reh = RequestErrorHandler(exc=exc)
return reh.process_message()

We have completed all the basic functionalities for a CRUD operation in a structured way. It’s this simple.

Let's run the application using the command

uvicorn app.main:app --env-file dev.env

Please ensure to run the Postgres docker container by applying the steps mentioned in the previous article.

Go to the swagger URL http://127.0.0.1:8000/docs/ and try executing CRUD APIs.

  1. Test create user API.

2. Test get all user's API.

3. Test get user by id API.

4. Pass incorrect id in get user by id API. Check out the error message here.

5. Test delete user API.

Summary

We have covered the complete production-ready code related to CRUD APIs, databases, settings, models & repositories. In the next article, we will cover

  1. API Documentation.
  2. Add correlation id to the API response.

A quick link to articles from this series:

We would be glad to hear suggestions from you. Stay tuned for the next part of this series. Thank you for reading.

The whole project is available in the GitHub repository.

If this article is helpful, follow me to see my next articles.

--

--

Mohit

Founder @SignalsIQ.AI | Prev @Co-Founder @getphyllo.com