Skip to content

Latest commit

 

History

History
111 lines (68 loc) · 2.33 KB

part-3.md

File metadata and controls

111 lines (68 loc) · 2.33 KB

Week 2 Part 3: SQLite and FastAPI Exercise

This exercise is based on Part 1 and Part 2.

Create a new project from zero. Do not reuse the week2-sqlite project.

Goal

Create a small database and API for books.

Your API should support:

  • GET / returns a welcome message
  • GET /books returns all books from SQLite

Part A: Create the Database

  1. Create a new folder called:
week2-books-api
  1. Open it in VS Code.

  2. Open a new VS Code terminal.

  3. Create and open the database from the project terminal:

sqlite3 books.db

Write and run your table creation and insert statements for steps 5–6 inside the sqlite> shell.

  1. Create a table called books with these columns:
  • id: INTEGER PRIMARY KEY AUTOINCREMENT
  • title: TEXT NOT NULL
  • author: TEXT NOT NULL
  • year: INTEGER NOT NULL
  1. 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.

  2. Use SELECT * FROM books; to check your data.

  3. Exit SQLite.

Part B: Create the FastAPI App

  1. Create and activate a virtual environment.

  2. Create requirements.txt with:

fastapi==0.141.1
uvicorn==0.52.4
  1. Install the requirements.

  2. Create main.py.

  3. Create a FastAPI app that connects to books.db. As in Part 2, build the database path relative to main.py, set connection.row_factory = sqlite3.Row, and use dict(row) to convert each returned record into a dictionary.

  4. 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.

Part C: Test

  1. Run the app with Uvicorn.

  2. Open:

http://127.0.0.1:8000/
  1. Open:
http://127.0.0.1:8000/books
  1. Stop the server.

Checklist

Before you finish, make sure:

  • books.db exists
  • the books table exists
  • at least three books are inserted
  • GET / works
  • GET /books returns 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.