Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
What the course covers
How HTTP and REST APIs work.
- How to call APIs with the
requestslibrary. - How to read and write JSON in Python.
- How to build APIs with Flask: routes, cookies, sessions, errors, and file uploads.
- How to render pages with Jinja and store data in sqlite3.
- How to run Flask with waitress and inside a Docker container.
- How to speed up API calls with threads and asyncio.
- How to build a modern API with FastAPI, plus an optional PCEP review.
Welcome to Alta3 Research Labs!
The lab is a Linux host. Your user is student. The prompt ends in $ for a normal user.
- You get a browser pane to view a web app on a port. You get a tmux pane for the shell.
- Each code block has a copy icon. Paste with right-click or
Ctrl+Shift+V. - VIRGIL is the AI coach for the lab. Ask it when a step is unclear.
Before You Begin This Course
The course expects Python basics. You should know functions, lists, dictionaries, loops, files, modules, errors, and classes.
- If those topics are new, take Introduction to Python first.
Getting Started
Vim: press i to insert, Esc to stop, :wq to save, and :q! to quit without saving.
- tmux:
Ctrl+bstarts a command.%splits left and right."splits top and bottom. - The labs ask you to keep all work in
~/mycode/.
Software Control Management
Lesson 007 compares GitHub and GitLab. Both are fine for the course.
- You make an account, a repo, and a personal access token.
- Then you set your git name and email and push from the terminal.
RESTful APIs and Client Access
An API returns data, not a web page. A URL is the address of the data.
- A GET asks for data. A POST sends data. A PUT updates data. A DELETE removes data. That set maps to CRUD.
- JSON is text. It looks like Python data, but it is not Python.
resp.json()turns a response into a dict or a list. - The type names change in JSON. A Python
dictbecomes an object. A list or tuple becomes an array.Truebecomestrue, andNonebecomesnull. requests.get(url)sends a GET.requests.post(url, json=data)sends a POST.requests.put(url, json=data)sends a PUT.resp.status_codetells you the result. 200 means OK. 404 means not found.pprintprints a big dict in a readable way.dict.keys()lists the keys. A loop walks a list of records.- A dev key is a private token from the API owner. NASA gives 1000 requests per hour with a key. The demo key is very limited.
- Swagger and OpenAPI describe an API in YAML or JSON. The file lists paths, methods, and examples.
- Good API design uses nouns in paths, such as
/users. The HTTP method is the verb. Examples help other developers use the API.
Building RESTful APIs with Flask
Flask is a small web framework. It is built on Werkzeug (WSGI) and Jinja.
app = Flask(__name__)makes the app.@app.route("/")binds a URL to a function.app.run(host="0.0.0.0", port=2224)starts it.- A route can take a variable:
@app.route("/hello/<name>"). The function receivesnameas an argument. - A cookie is a small text file on the client.
make_response()makes a response object.resp.set_cookie("userID", user)sets it.request.cookies.get("userID")reads it. Never put secrets in a cookie. - A session is like a cookie for short-lived data. Set
app.secret_keyfirst.session["username"] = "admin"stores a value.session.pop("username", None)removes it. redirect()sends the client to a new URL. Its status code defaults to 302.abort(404)returns an error code.- HTTP codes group by their first digit. 2xx is success. 3xx is a redirect. 4xx is a client error. 5xx is a server error.
- Flask-Limiter slows users who send too many requests. This protects the API from abuse.
- Uploads need a form with
multipart/form-data.request.files["file"]holds the file.secure_filename()cleans the name.MAX_CONTENT_PATHsets the size limit. - Jinja fills a template with data. Templates live in
templates/.render_template("page.html")returns the finished page. - sqlite3 is a small file database in the standard library.
sqlite3.connect("test.db")opens or makes it.conn.execute(...)runs SQL.conn.commit()saves.conn.close()ends it. - The inventory lab joins Flask and sqlite3. A web form adds a student to a table, and the app shows the list.
- The Flask dev server is for testing only. Waitress is a production WSGI server. It is pure Python and has no outside dependencies.
- Docker runs the app in a container. A
Dockerfilebuilds the image.docker build -t dune-app -f Dockerfile .builds it.
Additional Labs and Tools
Threads let a program start a task and do other work while it waits. threading.Thread(target=func) makes a thread. .start() begins it.
- Threads help with many API calls. Each call waits on the network, so the CPU is free. Without threads, each call blocks the next one.
- The
threadinglibrary gives you full control.concurrent.futuresis simpler when the tasks do not share state. Both are in the standard library. ThreadPoolExecutor(max_workers=5)runs a pool of tasks.as_completed()yields results as they finish. Keep the pool small so you do not overload the API.- asyncio is single-thread and single-process. Coroutines pause at
await.aiohttpmakes async HTTP requests. Use it for I/O-bound work, not CPU-bound work. - FastAPI is a newer API framework. It is fast. It uses type hints and Pydantic models. Uvicorn is the ASGI server.
- FastAPI writes its own docs.
/docsshows Swagger UI./redocshows ReDoc. Both update as you change the code.
Optional- PCEP Certification Guide
The exam has 30 questions in 45 minutes. You need 70% to pass.
- The review covers number systems, operators, loops, tuples, and error handling.
- These lessons repeat the Python basics you need for the exam.
Key commands and tools
python3 -m pip install requests flask fastapi "uvicorn[standard]" aiohttpresp = requests.get(URL)thenresp.json()andresp.status_coderesp = requests.post(URL, json=mydata)andrequests.put(URL, json=updated_data)from pprint import pprintthenpprint(vader)for key in data.keys():walks the keys of a dictapp = Flask(__name__),@app.route("/"), andapp.run(host="0.0.0.0", port=2224)@app.route("/hello/<name>")withdef hello_name(name): return f"Hello {name}"resp = make_response(...),resp.set_cookie("userID", user), andrequest.cookies.get("userID")app.secret_key = "...",session["username"] = ..., andsession.pop("username", None)redirect(url_for("index"))andabort(404)f.save(secure_filename(f.filename))render_template("upload.html")with templates in~/mycode/flaskapi/templates/conn = sqlite3.connect("test.db"),conn.execute("CREATE TABLE ..."), andconn.commit()threading.Thread(target=groundcontrol).start()with ThreadPoolExecutor(max_workers=5) as executor:andexecutor.submit(download_file, url)async with aiohttp.ClientSession() as session:thenawait resp.json()uvicorn main:app --host 0.0.0.0 --port 2224curl http://127.0.0.1:2224/items/6?q=altasudo docker build -t dune-app -f Dockerfile .python3 -m venv myenvandsource myenv/bin/activategit add *,git commit -m "API lab", andgit push originpython3 -m pip freeze | grep flaskchecks that a package is installed
Key terms
The words of this course in one table. Learn them before the quiz or exam.
| Term | Meaning |
|---|---|
| API | A service that gives data or actions to another program. |
| ASGI | The async standard between a Python web app and its server. |
| Client | The program that sends a request to a server. |
| Cookie | A small text file that a site stores on the client. |
| Coroutine | A function that can pause at await and resume later. |
| CRUD | Create, read, update, and delete: the four data actions. |
| Decorator | A line that starts with @ and adds behavior to a function. |
| Endpoint | One URL path and method of an API. |
| Flask | A small Python web framework for APIs and web pages. |
| GET | An HTTP method that asks for data. |
| HTTP | The protocol that carries web and API traffic. |
| Jinja | A template tool that fills HTML with data. |
| JSON | A text format for data, using objects and arrays. |
| POST | An HTTP method that sends new data. |
| PUT | An HTTP method that updates existing data. |
| Pydantic | A FastAPI helper that checks data types. |
| REST | A style for APIs that uses URLs and HTTP methods. |
| Route | A URL rule that Flask binds to a function. |
| Session | Short-term data kept for one user across requests. |
| SQLite | A small database that lives in one file. |
| Status code | A number in the response, such as 200 or 404. |
| Thread | A task that runs beside other tasks in one program. |
| Uvicorn | An ASGI server used to run FastAPI apps. |
| Waitress | A production WSGI server for Python web apps. |
| WSGI | The standard between a Python web app and a web server. |
Check yourself
Answer each question first, then open it to check the answer.
1Which HTTP method do you use to create a new resource?
POST. A GET reads, a PUT updates, and a DELETE removes.
2How do you turn an API response into Python data?
Call resp.json() on the response. It returns a dict or a list.
3Where does Flask look for templates by default?
In a folder named templates/, next to the Flask app file.
4Why must you set app.secret_key before you use sessions?
Flask uses the key to sign the session cookie. If the key is missing, Flask stops with an error when you use a session.
5What is the job of waitress?
It is a production WSGI server. It replaces the small Flask dev server when the app is public.
Useful links
Official documentation and pages for this course.
- Alta3 Research — alta3.com
- Alta3 on YouTube — @Alta3Research
- Alta3 on GitHub — github.com/alta3