This exercise is based on Part 1 and Part 2.
Create a new project from zero. Do not reuse the week2-sqlite project.
Create a small database and API for books.
Your API should support:
GET /returns a welcome messageGET /booksreturns all books from SQLite
- Create a new folder called:
week2-books-api
-
Open it in VS Code.
-
Open a new VS Code terminal.
-
Create and open the database from the project terminal:
sqlite3 books.dbWrite and run your table creation and insert statements for steps 5–6 inside the sqlite> shell.
- Create a table called
bookswith these columns:
id:INTEGER PRIMARY KEY AUTOINCREMENTtitle:TEXT NOT NULLauthor:TEXT NOT NULLyear:INTEGER NOT NULL
-
Insert at least three books of your choice. Use publication years for books, rather than film release years. For example, The Hobbit by J.R.R. Tolkien was published in
1937. -
Use
SELECT * FROM books;to check your data. -
Exit SQLite.
-
Create and activate a virtual environment.
-
Create
requirements.txtwith:
fastapi==0.141.1
uvicorn==0.52.4
-
Install the requirements.
-
Create
main.py. -
Create a FastAPI app that connects to
books.db. As in Part 2, build the database path relative tomain.py, setconnection.row_factory = sqlite3.Row, and usedict(row)to convert each returned record into a dictionary. -
Add:
GET /
GET /books
The home endpoint should return:
{"message": "Books API is running"}The books endpoint should return a JSON list of objects containing id, title, author, and year, ordered by id.
-
Run the app with Uvicorn.
-
Open:
http://127.0.0.1:8000/
- Open:
http://127.0.0.1:8000/books
- Stop the server.
Before you finish, make sure:
books.dbexists- the
bookstable exists - at least three books are inserted
GET /worksGET /booksreturns your database rows
After trying the exercise yourself, compare your work with the Part 3 reference solution.
Part 3 is complete. Continue to Homework 1.