
Already know some of this? A 2-minute test skips the lessons you know.
Take the placement testA free 94-lesson course built from freeCodeCamp.org's 19h 00m of YouTube video. 12 days at 90 minutes a day, with study notes and a quiz in every lesson. A 2-minute placement test skips what you already know.
Taught by freeCodeCamp.org on YouTube. Videos play in YouTube's own player, so the creator keeps every view.
Understand the course scope, tech stack (FastAPI, PostgreSQL, SQLAlchemy, Pydantic, Alembic, Docker, Heroku, Ubuntu, GitHub Actions), and the social media API project with posts, users, authentication, and voting features.
Install Python and VS Code on macOS, configure the Python extension, create a project folder, and verify the interpreter selection in VS Code.
Explain why virtual environments are needed for dependency isolation, then create and activate a virtual environment on both Windows and Mac using `python -m venv`.
Install FastAPI with all optional dependencies using `pip install fastapi[all]`, create a minimal FastAPI app instance, run it with Uvicorn and the `--reload` flag, and verify the 'Hello World' response.
Break down a path operation into its decorator (HTTP method, path) and function (logic, return value), explain the `@app.get('/')` syntax, and demonstrate auto-reload during development.
Install Postman, send GET and POST requests, inspect JSON responses, and save requests into a collection for reuse.
Define Pydantic models (BaseModel) for request/response validation, use field types (str, int, bool, Optional), set defaults, and demonstrate automatic 422 errors on invalid input.
Implement Create, Read (all & one), Update, Delete for posts using a Python list, handle path parameters, type conversion, 404 errors, and 201/204 status codes.
Set custom status codes (201 Created, 204 No Content) via the decorator's `status_code` parameter and `status.HTTP_*` constants.
Explain relational databases and DBMS, install PostgreSQL on Windows and Mac (default port 5432, password 'password123'), and introduce pgAdmin GUI.
Create a database and tables via pgAdmin, define columns (serial, varchar, boolean, timestamp), set primary keys, unique constraints, NOT NULL, and server defaults (e.g., `now()` for created_at).
Run `SELECT * FROM table`, filter columns, use `WHERE` with `=`, `>`, `>=`, `<`, `<=`, `!=`, `AND`/`OR`, `IN`, `LIKE` for pattern matching, and `ORDER BY`.
Paginate with `LIMIT`/`OFFSET`, insert rows with `RETURNING *`, delete with `WHERE`, update with `SET`/`WHERE`/`RETURNING *`, and commit transactions.
Drop test tables, create `fastapi` database, build `posts` table with id, title, content, published, created_at, owner_id, connect via `psycopg2` using a connection URL, and implement a `get_db` dependency with `yield` for session management.
Implement GET all, GET one, POST create (with `RETURNING *` and `commit`), DELETE (with `RETURNING *`), PUT update (with `WHERE` and `RETURNING *`) using parameterized queries (`%s`) to prevent SQL injection.
Explain ORM benefits, install SQLAlchemy, define `Base` with `declarative_base`, create `Post` model (id, title, content, published, created_at), configure engine/sessionmaker, and add `get_db` dependency.
Implement GET all (`query().all()`), GET one (`filter().first()`), POST create (`add`, `commit`, `refresh`), DELETE (`delete`, `commit`), PUT update (`update`, `commit`, `query().first()`), and verify auto-table-creation on startup.
Add `created_at` column with `TIMESTAMP(timezone=True)`, `nullable=False`, `server_default=text('now()')`, drop/recreate table to apply schema changes, and verify default timestamp on insert.
Distinguish Pydantic schemas (request/response validation) from SQLAlchemy models (DB table definition), and explain why both are needed.
Create `PostBase`, `PostCreate`, `PostUpdate`, `PostOut` schemas using inheritance, move schemas to `schemas.py`, set `response_model` on routes, and exclude password from user response.
Create `UserCreate` schema with `EmailStr`, implement `/users` POST route, hash passwords with `passlib`/`bcrypt` in `utils.hash()`, store hash, and verify login rejects plain passwords.
Explain stateless JWT auth (header, payload, signature), HS256 algorithm, token expiration, and the login flow: credentials -> verify -> create token -> return token -> client sends token in Authorization header.
Implement `create_access_token` with `jose.jwt.encode`, embed `user_id` and `exp` claim, use `OAuth2PasswordRequestForm` dependency for login, swap `email` for `username` field, and test with form-data in Postman.
Create `verify_access_token` to decode JWT, validate signature/expiration, raise 401 on failure, implement `get_current_user` to fetch user from DB via token's `user_id`, and attach user to protected routes.
Add `current_user: User = Depends(get_current_user)` to protected routes (create, delete, update posts), test 401 on missing/invalid token, set token expiry to 1 min to verify 401 after expiration.
Create Postman environments (dev/prod) with `url` variable, reference via `{{url}}`, auto-save JWT `access_token` from login response to environment via `pm.environment.set()`, and use variable in other requests.
Add `owner_id` FK to `posts` table referencing `users.id` with `ondelete=CASCADE` via pgAdmin and SQLAlchemy (`ForeignKey`, `ondelete='CASCADE'`), drop/recreate table to apply, verify cascade delete.
Define `owner` relationship on `Post` model (`relationship('User', back_populates='posts')`), join `posts` + `users` in queries, select specific columns (`Post.title`, `User.email`), and handle ambiguous column names with table prefixes.
Add optional query params `limit` (default 10), `skip` (default 0), `search` (title contains), apply `.limit()`, `.offset()`, `.filter(Post.title.contains())` in SQLAlchemy, and handle URL-encoded spaces (`%20`).
Remove unused imports (psycopg2, typing, random, schemas), move DB connection logic to `database.py`, create `.env` file with DB credentials, secret key, algorithm, expiry, load via `BaseSettings` with `env_file='.env'`, add `.env` to `.gitignore`.
Design `votes` table with `post_id`, `user_id` as composite PK (prevents duplicate likes), add FKs to `posts` and `users`, implement `/vote` POST route with direction (1=like, 0=unlike), validate post exists, and enforce unique vote per user/post.
Install Alembic, `alembic init`, configure `env.py` with `target_metadata=Base.metadata`, `sqlalchemy.url` from settings, generate revisions with `alembic revision --autogenerate`, run `alembic upgrade head`, and disable SQLAlchemy `create_all`.
Add `CORSMiddleware` with `allow_origins=['*']`, `allow_credentials=True`, `allow_methods=['*']`, `allow_headers=['*']` to enable cross-origin requests from browsers.
Initialize Git, commit, add GitHub remote, push, create Heroku app (`heroku create`), add `Procfile` (`web: uvicorn app.main:app --host 0.0.0.0 --port $PORT`), push to Heroku (`git push heroku main`), set config vars, and verify deployment.
Create DigitalOcean droplet, SSH in, update packages, install Python/pip/Postgres, set Postgres password, configure `listen_addresses='*'`, create DB/user, set env vars in `~/.profile`, run Alembic migrations, install Gunicorn (`gunicorn -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000`), configure Nginx reverse proxy, set up domain DNS, run Certbot for HTTPS, enable UFW firewall (allow 80, 443, 22, 5432).
Write `Dockerfile` (Python 3.9 slim, `WORKDIR`, copy `requirements.txt`, `pip install`, copy code, `CMD uvicorn --host 0.0.0.0`), create `docker-compose.yml` with `api` (build, env_file, ports, depends_on) and `postgres` (image, named volume for `/var/lib/postgresql/data`), run `docker compose up -d`.
Add bind mount (`./app:/app`) to sync code changes without rebuild, push image to Docker Hub (`docker tag`, `docker push`), and distinguish dev vs prod compose files (prod uses pre-built image, no bind mount).
Install pytest, create `tests/test_calculations.py`, write `test_add` with `assert add(5,3)==8`, run `pytest -v -s`, rename files to `test_*.py` for auto-discovery, and use `assert` for pass/fail.
Test subtract/multiply/divide, use `@pytest.mark.parametrize` for multiple inputs, test class methods, and handle floating-point conversion in Pydantic validation.
Create `@pytest.fixture` for `bank_account` (yield for setup/teardown), inject into tests, combine with `parametrize` for deposit/withdraw scenarios, and explain fixture scopes (function, module, session).
Use `with pytest.raises(InsufficientFunds)` to expect custom exceptions, import `TestClient` from `fastapi.testclient`, create `client = TestClient(app)`, and test routes with `client.get/post` returning response objects.
Override `get_db` dependency in `conftest.py` with test engine/sessionmaker pointing to `fastapi_test` DB, create fixture `session` that `Base.metadata.create_all` before `yield` and `drop_all` after, ensure clean slate per test.
Create `test_user` fixture that POSTs to `/users` via `client`, returns user dict with password, implement `login_user` fixture dependent on `test_user`/`client`, decode JWT in test to verify `user_id` and `token_type=bearer`.
Move shared fixtures to `conftest.py`, organize tests into `test_posts.py`, `test_users.py`, `test_votes.py`, run full suite (`pytest -v`), and verify all 46 tests pass.
Define CI (pull code, install Python, upgrade pip, install deps, run pytest) and CD (deploy to Heroku/Ubuntu) jobs in `.github/workflows/ci-cd.yml`, use `needs: [build]` for sequential deploy, store secrets in GitHub Environments (testing/production), and verify failed tests block deployment.
Use `akhilesh/heroku-deploy` action with `heroku_api_key`, `heroku_app_name`, `email` secrets, pull repo in deploy job, and verify automatic deployment on successful build.
Add SSH deploy job with `appleboy/ssh-action`, use secrets for `HOST`, `USERNAME`, `PASSWORD`, run `cd /app/source && git pull && sudo systemctl restart api`, fix `sudo` password prompt with `echo $PASSWORD | sudo -S systemctl restart api`.