Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Cursus 11Naam in de cursus: Building APIs with Python

Building APIs with Python

Course 11 of 13 in the Alta3 Academy library. Alta3 Academy self-paced course.

Notitie

My result — Lessons read: all 42/42; Course progress: 100%.

  • 14 Lessen
  • 6 Commando's
  • 2 Labs

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

11.1

What the course covers

How HTTP and REST APIs work.

  • How to call APIs with the requests library.
  • 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.

11.2

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.

11.3

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.

11.4

Getting Started

Vim: press i to insert, Esc to stop, :wq to save, and :q! to quit without saving.

  • tmux: Ctrl + b starts a command. % splits left and right. " splits top and bottom.
  • The labs ask you to keep all work in ~/mycode/.

11.5

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.

11.6

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 dict becomes an object. A list or tuple becomes an array. True becomes true, and None becomes null.
  • requests.get(url) sends a GET. requests.post(url, json=data) sends a POST. requests.put(url, json=data) sends a PUT.
  • resp.status_code tells you the result. 200 means OK. 404 means not found.
  • pprint prints 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.

11.7

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 receives name as 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_key first. 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_PATH sets 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 Dockerfile builds the image. docker build -t dune-app -f Dockerfile . builds it.

11.8

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 threading library gives you full control. concurrent.futures is 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. aiohttp makes 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. /docs shows Swagger UI. /redoc shows ReDoc. Both update as you change the code.

11.9

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.

11.10

Key commands and tools

  • python3 -m pip install requests flask fastapi "uvicorn[standard]" aiohttp
  • resp = requests.get(URL) then resp.json() and resp.status_code
  • resp = requests.post(URL, json=mydata) and requests.put(URL, json=updated_data)
  • from pprint import pprint then pprint(vader)
  • for key in data.keys(): walks the keys of a dict
  • app = Flask(__name__), @app.route("/"), and app.run(host="0.0.0.0", port=2224)
  • @app.route("/hello/<name>") with def hello_name(name): return f"Hello {name}"
  • resp = make_response(...), resp.set_cookie("userID", user), and request.cookies.get("userID")
  • app.secret_key = "...", session["username"] = ..., and session.pop("username", None)
  • redirect(url_for("index")) and abort(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 ..."), and conn.commit()
  • threading.Thread(target=groundcontrol).start()
  • with ThreadPoolExecutor(max_workers=5) as executor: and executor.submit(download_file, url)
  • async with aiohttp.ClientSession() as session: then await resp.json()
  • uvicorn main:app --host 0.0.0.0 --port 2224
  • curl http://127.0.0.1:2224/items/6?q=alta
  • sudo docker build -t dune-app -f Dockerfile .
  • python3 -m venv myenv and source myenv/bin/activate
  • git add *, git commit -m "API lab", and git push origin
  • python3 -m pip freeze | grep flask checks that a package is installed

11.11

Key terms

The words of this course in one table. Learn them before the quiz or exam.

TermMeaning
APIA service that gives data or actions to another program.
ASGIThe async standard between a Python web app and its server.
ClientThe program that sends a request to a server.
CookieA small text file that a site stores on the client.
CoroutineA function that can pause at await and resume later.
CRUDCreate, read, update, and delete: the four data actions.
DecoratorA line that starts with @ and adds behavior to a function.
EndpointOne URL path and method of an API.
FlaskA small Python web framework for APIs and web pages.
GETAn HTTP method that asks for data.
HTTPThe protocol that carries web and API traffic.
JinjaA template tool that fills HTML with data.
JSONA text format for data, using objects and arrays.
POSTAn HTTP method that sends new data.
PUTAn HTTP method that updates existing data.
PydanticA FastAPI helper that checks data types.
RESTA style for APIs that uses URLs and HTTP methods.
RouteA URL rule that Flask binds to a function.
SessionShort-term data kept for one user across requests.
SQLiteA small database that lives in one file.
Status codeA number in the response, such as 200 or 404.
ThreadA task that runs beside other tasks in one program.
UvicornAn ASGI server used to run FastAPI apps.
WaitressA production WSGI server for Python web apps.
WSGIThe standard between a Python web app and a web server.

11.12

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.

Oefenen

Alle commando's in dit hoofdstuk