Connecting Your Database
In this lesson, you’ll visit http://127.0.0.1:8000/docs
to visit your app’s API documentation.
00:00
Connecting Your Database. With the database model in place, you can now link your app to it. For now, you’ll add most of the code to communicate with your database to main.py
.
00:16
First, you import the secrets
module, Depends
from FastAPI
, Session
from sqlalchemy
,
00:37
and your internal models
module. You then import SessionLocal
and engine
from your database
module.
00:57
This line binds your database engine with models.Base.metadata.create_all()
. If the database that you defined in engine
doesn’t exist yet, then it will be created with all model tables once you run your app for the first time. Here, you define the get_db()
function, which will create and yield new database sessions with each request.
01:20
Once the request is finished, you close the session with db.close()
. You use the try
… finally
block to close the database connection in any case, even when an error occurs during the request.
01:38
This path operation decorator makes sure that the create_url()
function that follows responds to any POST requests at the forward /url
path.
01:49
Here, you define create_url
, which requires a URLBase
schema as an argument and depends on a database session. By passing get_db
into Depends()
, you establish a database session for the request and close the session when the request is finished.
02:11
These lines provide random strings for key
and secret_key
.
02:29
Next, you create a database entry for your target_url
.
02:47
These two lines add key
and secret_key
to db_url
to match the required URLInfo
schema that you need to return at the end of the function. Finally, db_url
is returned.
03:03
You may feel that the code you’ve just added overwhelms the scope of the create_url()
function, and your intuition is correct. Indeed, You may find better places to create random strings and perform database actions. But it’s okay not to be perfect right away.
03:20
Check if the app works as expected before tackling its shortcomings. Go to the docs URL … and click POST for the /url
route. Click Try it out and then scroll down to the Request body section and enter a target URL, remembering to enclose the URL in double quotes.
03:45
Scroll down and click Execute, and in the Response body section below, you’ll see the response. It’s the data that you defined in schemas.py
.
03:59
When the server restarted, SQLAlchemy automatically created your database in the location you defined in the DB_URL
environment variable. If you used sqlite:///./shortener.db
, as the value of DB_URL
, then there should be a file named shortener.db
in the root directory of your project. That is your SQLite database.
04:24
So far, the database contains the table that you defined in models.py
, but it doesn’t contain any data. To have a look, fire up your Python interpreter and follow the command seen on-screen.
04:40
First you import SessionLocal
, and then you instantiate a database connection. Next, you import the URL
model, and you use it as an argument for the database query to request all database entries for URL
.
05:02
The returned list is empty because the urls
table doesn’t contain any data yet. Keep this session open for now and go to the URL seen on-screen and use the POST endpoint to create some URLs.
05:50
Once you’ve used the POST endpoint of your app, back in the terminal, verify that the request created the database entries accordingly. With this line, you are querying all entries of the URL
table. In return, you get a list of all database entries that you created with the POST request that you sent over to your API.
06:13 You can now store data in your database, and it persists across multiple user sessions. That’s a significant milestone for your URL shortener. This might make you as the developer happy, but to make your users happy, you need to add the vital feature of actually forwarding to the targeted URL.
06:33 In the next section of the course, you’ll enhance your app to forward a shorten URL to the target.
Become a Member to join the conversation.