Skip to article frontmatterSkip to article content

Answer to a need but which one?

Simplified development framework

Basically a spiritual guide, allowing to simply develop specific applications.


Framework vs Library

Frameworks, Libraries, same thing?

Libraries

Set of programs performing specific operations, that you will use punctually within your programs following your own logic.

For example NumPy in Python 🐍 is a library

Framework

Development framework in which the developer comes to register, i.e. develop functionalities/behaviors. There it is no longer the developer who sets his logic but the framework.

A code with holes 🕳️ in a way


Frontend, backend

⚠️ Web framework a very, too, generic term ⚠️

Frontend framework

Focused on client-side application development

Backend framework

Focused on server-side development


backend frameworks: the main principles

To this a complete framework adds functionalities of:

Web Template, Security, Access to databases


FastAPI Framework

Python 🐍 “lightweight” framework developed since 2018.



🚧 “lightweight” framework does not mean “not usable on big projects” ⚠️

Netflix, Microsoft, Uber, ... use FastAPI for certain parts of their backends

very light and minimalist core, but super powerful


Basic setup

Installation

pip install fastapi[standard]

we will also install httpie to test APIs in command line
it’s just a very practical development tool, no need for this dependency in production

# ceci installe la commande http, disponible depuis le terminal
pip install httpie

Hello world in FastAPI (run it)

let’s create a file hello.py with this:

# in hello.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello World"}

? What is @app.get('/') ?

and to launch it type this

# in the terminal

fastapi dev hello.py

Hello world in FastAPI (use it)

after which we can query our API... we have the choice between:

open a web browser at the address
http://localhost:8000
do it, you should see this:

{"message":"Hello World"}

use http(ie) in command line

# in verbose version
http GET http://localhost:8000

# in concise version
http :8000

the two forms are equivalent
and in both cases observe that http shows us the HTTP Headers of the response


Routes

@app.get is a decorator that allows to associate a function with a URL (here of type GET).
Obviously a web application is more than that, we want to manage several URLs, and of several types.
So a FastAPI application is essentially a collection of routes.

For example:

@app.post("/items/")
def create_item(item: Item):
    # code to create an item

@app.get("/items/")
def create_item(item: Item):
    # code to list items

@app.get("/items/{item_id}")
def read_item(item_id: int):
    # code to read an item

We’re done ...

... or not actually: we’re going to put all this into practice with an exercise