Chapter 5 · Project and Next Steps
Summary, Cheat Sheet and What's Next
- Page 22 of 22
- 15 min read
You started this tutorial without having used Git or built a server. You can now work in a terminal, keep a project in a Git history, publish it, call web APIs safely from Python, build and validate your own API with FastAPI, and prove it works with tests. This page puts all of it in one place: cheat sheets to keep open while you work, a glossary, the mistakes that cost beginners the most time, and what comes next.
What you will learn
- The commands and ideas of the whole beginner tutorial on one page, grouped by task.
- The glossary of words you will keep meeting in AI backend work.
- The common mistakes to check yourself against, and how to keep practising.
- What the advanced tutorial covers, and where the wider AI path goes next.
What you can do now
- Move around the terminal, set environment variables, create a virtual environment or a uv project, and keep secrets out of code.
- Create commits with clear messages, read history and diffs, undo mistakes without losing work, and use branches and merges.
- Push to a remote, open a pull request, and write a README that helps.
- Explain a request and a response, choose the right method and status code, and test an API with
curl. - Call APIs from Python with timeouts, retries and pagination, and build a FastAPI service that validates input and returns proper errors.
- Write pytest tests with a faked upstream, and ship the result through a reviewed pull request.
Cheat sheet 1: terminal, environments and packages
| Task | Command |
|---|---|
| Where am I, what is here | pwd, ls -la |
| Move around | cd folder, cd .., cd ~, cd - |
| Create, copy, move, delete | mkdir -p a/b, touch f, cp a b, mv a b, rm f, rm -r folder (no undo: there is no recycle bin) |
| Look inside files | cat f, head -n 5 f, tail -n 5 f, grep -n "text" f |
| Pipes and redirection | cmd1 | cmd2 (output into input), > f (overwrite), >> f (append), 2>&1 (errors too) |
| Help | cmd --help, man cmd |
| Environment variable | export KEY=value, echo "$KEY", in Python os.environ["KEY"] or os.getenv("KEY") |
| Secrets in a file | .env (never committed) read with python-dotenv; commit .env.example with fake values |
| venv and pip | python -m venv .venv, source .venv/bin/activate, pip install -r requirements.txt, pip freeze > requirements.txt |
| uv | uv init, uv add requests, uv add --dev pytest, uv sync, uv run python main.py; files pyproject.toml and uv.lock |
| On Windows | Git Bash / WSL / macOS / Linux | PowerShell |
|---|---|---|
| Set a variable | export KEY=value | $env:KEY = "value" |
| Activate a venv | source .venv/bin/activate | .venv\Scripts\Activate.ps1 |
| Show a file | cat f | Get-Content f |
Cheat sheet 2: Git and GitHub
| Task | Command |
|---|---|
| One-time setup | git config --global user.name "Nadia Rahman", git config --global user.email "[email protected]", git config --global init.defaultBranch main |
| Start a repository | git init, or git clone URL |
| See the state | git status, git status --short |
| Stage and commit | git add file, git add -p, git commit -m "Add course filter" |
| History | git log --oneline --graph --decorate --all, git show <hash> |
| Differences | git diff (unstaged), git diff --staged, git diff main...feature |
| Ignore files | .gitignore; check with git check-ignore -v file; stop tracking with git rm --cached file |
| Discard unstaged changes | git restore file |
| Unstage | git restore --staged file |
| Fix the last commit | git commit --amend (only if not pushed) |
| Undo commits | git reset --soft HEAD~1 (keep changes staged), --mixed (default, keep changes), --hard (throws changes away); on shared history use git revert <hash> |
| Branches | git branch, git switch -c feature/x, git switch main, git branch -d feature/x |
| Merge | git switch main, git merge feature/x (add --no-ff for a merge commit); on a conflict edit the marked files, git add, git commit |
| Remotes | git remote add origin URL, git remote -v, git push -u origin branch, git fetch, git pull |
| Pull request flow | branch, commit, push, open PR with a description, review, push fixes, merge, delete the branch |
| GitHub CLI | gh pr create, gh pr view --web |
| Log in | HTTPS with a fine-grained personal access token, or SSH with an ed25519 key |
The rule behind most of the table: git restore and git reset --hard change files in your working folder, git revert adds a new commit, and a commit you have not pushed can still be amended. If you are unsure, make a branch first: git switch -c backup costs nothing.
Cheat sheet 3: HTTP, curl and requests
| Method | Meaning | Has a body | Typical success |
|---|---|---|---|
| GET | read a resource | no | 200 |
| POST | create a resource, or run an action | yes | 201 (created) or 200 |
| PUT | replace a resource completely | yes | 200 or 204 |
| PATCH | change part of a resource | yes | 200 |
| DELETE | remove a resource | usually no | 204 or 200 |
| Status | Meaning | What to do |
|---|---|---|
| 200 / 201 / 204 | OK / created / success with no body | carry on |
| 301, 304 | moved permanently, not modified (use your cached copy) | follow the new URL, reuse the cache |
| 400 | malformed request | fix the request |
| 401 | not authenticated (no or bad credentials) | send a valid key or token |
| 403 | authenticated, but not allowed | ask for permission; retrying will not help |
| 404 | no such resource | check the URL and the id |
| 409 | conflict with the current state | resolve the clash (for example a duplicate) |
| 422 | well-formed, but the values are invalid | read the error list, fix the fields |
| 429 | too many requests | wait for Retry-After, then retry |
| 500 | the server has a bug | not your request: report it, maybe retry |
| 502, 503 | bad gateway, service unavailable | retry with a backoff |
The first digit is the family: 2xx success, 3xx redirection, 4xx the client made a mistake, 5xx the server did. That is why a 4xx is usually not worth retrying, while a 429 or 503 is.
| Task | curl | requests |
|---|---|---|
| GET | curl -s URL | requests.get(url, timeout=5) |
| Query string | curl -s "URL?level=beginner" | params={"level": "beginner"} |
| Headers | -H "X-API-Key: key" | headers={"X-API-Key": key} |
| Bearer token | -H "Authorization: Bearer TOKEN" | headers={"Authorization": f"Bearer {token}"} |
| JSON body | -X POST -H "Content-Type: application/json" -d '{"a": 1}' | requests.post(url, json={"a": 1}, timeout=5) |
| Status and headers | -i (headers too), -v (the whole exchange), -w "%{http_code}" | r.status_code, r.headers |
| Parse the body | | python -m json.tool | r.json() |
| Fail on 4xx/5xx | --fail | r.raise_for_status() |
| Reliability rule | In code |
|---|---|
| Always set a timeout (requests has none by default) | timeout=5, or (3, 10) for connect and read |
| Catch the right errors | requests.exceptions.Timeout, ConnectionError, HTTPError, all under RequestException |
| Retry only what can succeed later | 429, 502, 503, 504 and timeouts; never 400, 401, 403, 404, 422 |
| Back off between retries | wait 1 s, 2 s, 4 s, ..., and obey Retry-After |
| Reuse connections | session = requests.Session() |
| Read all pages | loop while the response gives a next_page, with a page limit |
| Keys come from the environment | os.environ["API_KEY"], never a string in the code |
Cheat sheet 4: FastAPI, Pydantic and pytest
| Task | Code |
|---|---|
| Create the app, run it | app = FastAPI(); fastapi dev (reload, for development), fastapi run main.py --port 8000 (for running) |
| A route | @app.get("/courses/{course_id}") then def get_course(course_id: int): ... |
| Query parameter | def list_courses(level: str | None = None, page: int = 1) |
| Request body | def create(review: ReviewIn) where ReviewIn(BaseModel) |
| Constraints | rating: int = Field(ge=1, le=5), text: str = Field(min_length=3, max_length=500) |
| Response shape | @app.post("/reviews", response_model=ReviewOut, status_code=201) |
| Raise an error | raise HTTPException(status_code=404, detail="Course not found") |
| Automatic docs | /docs (Swagger UI), /redoc, /openapi.json |
| Test client | client = TestClient(app), then client.get("/health"), with pip install pytest httpx2 or uv add --dev pytest httpx2 |
| Run tests | pytest -q, pytest -k name, pytest -x (stop at the first failure) |
| Fake a dependency | monkeypatch.setattr(module, "function", fake); patch the name where it is looked up |
| Many cases, one test | @pytest.mark.parametrize("value, expected", [...]) |
| Shared setup | fixtures in conftest.py |
A route returns data and FastAPI turns it into JSON with the right Content-Type. Invalid input never reaches your function: Pydantic rejects it with a 422 that lists every problem. The request lifecycle is the same in every backend: parse the request, validate it, run your logic, shape the response, set the status code.
Try the cheat sheet in code
A cheat sheet you only read is forgotten in a week. This short program quizzes you on the status codes. It takes a fixed list of codes, so the answers are the same every time you run it:
STATUS = {
200: "OK",
201: "Created",
204: "No Content",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
409: "Conflict",
422: "Unprocessable Content",
429: "Too Many Requests",
503: "Service Unavailable",
}
FAMILY = {2: "success", 3: "redirection", 4: "client error", 5: "server error"}
def describe(code):
return f"{code} {STATUS[code]} ({FAMILY[code // 100]})"
def should_retry(code):
# Only problems that can disappear by themselves are worth retrying.
return code in (429, 502, 503, 504)
for code in (200, 404, 422, 429, 503):
print(describe(code), "-> retry" if should_retry(code) else "-> do not retry")200 OK (success) -> do not retry
404 Not Found (client error) -> do not retry
422 Unprocessable Content (client error) -> do not retry
429 Too Many Requests (client error) -> retry
503 Service Unavailable (server error) -> retryNotice that the retry rule is a single line. Writing the rule down as a function is the same habit as writing it down in a cheat sheet, except that you can test it. Here is a second helper that turns the tutorial into a checklist you can paste into a pull request description before you ask for review:
CHECKS = {
"Code": ["Tests pass with the upstream faked", "Every outbound call has a timeout"],
"Git": ["Small commits with clear messages", "No .env, .venv or data files in the diff"],
"Docs": ["README explains what, run, use, test, configure"],
}
def checklist(title):
lines = [f"## Ready to merge: {title}"]
for area, items in CHECKS.items():
lines.append(f"### {area}")
lines.extend(f"- [ ] {item}" for item in items)
return "\n".join(lines)
print(checklist("Data Explorer API"))## Ready to merge: Data Explorer API
### Code
- [ ] Tests pass with the upstream faked
- [ ] Every outbound call has a timeout
### Git
- [ ] Small commits with clear messages
- [ ] No .env, .venv or data files in the diff
### Docs
- [ ] README explains what, run, use, test, configureGlossary
| Term | Meaning |
|---|---|
| Terminal / shell | the window where you type commands / the program that reads and runs them (bash, zsh, PowerShell) |
| Environment variable | a named setting outside your code, such as API_KEY, read at run time |
| Virtual environment | a private folder of Python packages for one project |
| Lock file | the exact versions that were installed (uv.lock), so every machine gets the same ones |
| Repository | a project folder plus its full history, stored in .git |
| Working tree / staging area | your files as they are now / the set of changes chosen for the next commit |
| Commit | a snapshot of the project with a message, an author and a pointer to its parent |
| Branch | a movable name for one line of commits |
| Merge conflict | two branches changed the same lines; you decide the result |
| Remote / origin | another copy of the repository, usually on GitHub / the default name for it |
| Pull request | a request to merge a branch, with a place for description and review |
| Client / server | the program that asks / the program that answers |
| Request / response | one message to the server (method, URL, headers, body) / the reply (status, headers, body) |
| Endpoint / route | one URL and method your API answers, and the function behind it |
| JSON | the text format APIs use to send objects, lists, strings and numbers |
| REST | a style where URLs name resources and HTTP methods are the verbs |
| API key / bearer token | a secret that identifies the caller, sent in a header |
| Timeout | the longest you will wait for a reply |
| Retry / backoff | trying again after a failure / waiting longer each time |
| Pagination | returning a long list in pages |
| Upstream | the service your service depends on (a data API, an LLM provider) |
| Validation | checking input against rules before using it (Pydantic does it for FastAPI) |
| Fixture / mock / fake | shared test setup / a stand-in object / a simple working stand-in such as a fake upstream |
| CI | continuous integration: a server that runs your tests on every push |
Common mistakes: a recap
- Committing a secret. Once pushed, it is leaked, even if you delete the file later. Fix:
.gitignorefirst,.env.examplefor the shape, and if it happens anyway, rotate the key before anything else. - Using
git reset --hardorrm -rwithout looking. Both are final. Fix:git statusandgit difffirst, or make a backup branch. - Rewriting history that others already have.
amendandreseton pushed commits cause trouble for teammates. Fix: usegit reverton shared branches. - Working on
maindirectly. Fix: one branch per change, merged through a pull request. - Calling an API without a timeout. One slow upstream can freeze your whole service. Fix: a timeout on every call, and a clear error when it fires.
- Retrying everything. Repeating a 401 or a 422 never helps, and hammering a rate-limited service makes it worse. Fix: retry only 429, 5xx and timeouts, with a backoff.
- Trusting what an upstream returns. Missing fields, wrong types and HTML error pages all happen. Fix: validate the response with a Pydantic model before using it.
- Returning the wrong status code. A 200 with
{"error": ...}hides failures from clients and monitors. Fix: 201, 404, 422 and the others mean something; use them. - Testing only the happy path, or against the real service. Fix: fake the upstream, and test timeouts, bad data and invalid input too.
- Never running from a fresh clone. Fix: clone,
uv sync,uv run pytestbefore you call it done.
How to keep practising
- Use Git for everything you write, including notes and small scripts. Habit comes from repetition, not from reading.
- Extend the Data Explorer API: a new endpoint, a new filter, one more failure case, each with a branch, a test and a pull request.
- Read other people's projects: open a well-known Python repository on GitHub and read its README, its
.gitignore, its tests and its commit history. - Break things on purpose: stop the Practice API and watch your timeouts and errors; make a merge conflict on purpose and resolve it; commit a fake secret in a throwaway repository and practise cleaning up.
- Wrap an API you like (a weather service, a public dataset) in your own small FastAPI service with validation and tests.
- Review your own pull request with the checklist from the project before you ask anyone else to.
What comes next
The next tutorial is Git, APIs and Backend for AI: Advanced. It takes the same tools to production level, in six chapters:
- Git and GitHub Like a Professional: stash, interactive rebase, cherry-pick, reflog, tags and releases, team workflows, and Git for AI projects (LFS, DVC, removing leaked secrets).
- API Design and API Clients: HTTP in depth, OAuth and tokens, pagination, rate limits, idempotency, webhooks and streaming, and httpx with async clients.
- Production FastAPI: project architecture, dependencies and lifespan, middleware, SQLAlchemy with Alembic, authentication, caching and rate limiting, and professional testing.
- AI Services and Security: serving a machine learning model, a backend for LLM applications with streaming and cost tracking, and API security.
- Ship It: Docker, Docker Compose, GitHub Actions and deployment.
- Practice and Capstone: a graded practice lab and a capstone: a production-ready AI backend.
After that the path continues with Prompt Engineering, which is where you learn to get reliable results from LLMs, and then the AI Engineer path: LLM APIs, RAG, agents, MCP, evaluations and LLMOps. Every one of those topics is built on what you practised here: calling APIs safely, serving your own, and shipping it with tests and a clean Git history.
Summary
- The terminal, environments and uv give every project its own tools and keep secrets out of code.
- Git records snapshots; branches, pull requests and reviews let you change them safely, and restore, reset and revert undo mistakes.
- HTTP is methods plus status codes plus headers plus a body;
curlandrequestslet you speak it, with a timeout, a retry rule and validation each time. - FastAPI and Pydantic turn Python functions into validated endpoints with correct status codes; pytest with a faked upstream keeps them honest.
- Practise on real projects, and move on to the advanced tutorial when you can build the Data Explorer API from scratch without the page open.
Next: Git, APIs and Backend for AI: Advanced, then Prompt Engineering.

