From the course: Build REST APIs with FastAPI

Unlock this course with a free trial

Join today to access over 24,200 courses taught by industry experts.

Working with databases

Working with databases

At one point or another, you're going to work with a database. And when working with databases, we have two main issues with web servers. These are not unique to FastAPI, but you need to handle them. The first thing is there's no main to using FastAPI utility to run our code. So there's no entry point and we need to connect to the server somehow. The second thing is that for every request, we want to get the cursor. FastAPI solves these issues with two tools it gives us. One is a lifespan event. A lifespan event lets you run code once when the server starts up before it receiving requests, and second after the server shuts down. And this is where we're going to connect to our database and then close the connection. The second one is a dependency or dependency injection. And you can tell it for this request I need this resource. Let's have a look. We have an application that saves trades in a database. So we have time, user, symbol, price, volume, how many shares, and decide if it's a…

Contents