Skip to article frontmatterSkip to article content

Small practical break

Objective: Set up an API allowing access to CSV file content

You have https://github.com/ue22-p25/backend-apitester-frontend a ready-made frontend!
And you have https://github.com/ue22-p25/backend-apitester-skeleton a backend to complete

The backend API must imperatively respect the routes documented in the README.


Tip #1: auto-reload

and same for the frontend by the way; if you intend to touch it, it’s better to launch it with vite, so it restarts by itself at each modification


Tip #2: typed parameters

# untyped parameter

@app.route('/hello/<name>')
  def hello(name):
    # here name is a simple str
    # it's up to you 
    # to check its content
    return f'Hello, {name}!'
# here the parameter is typed

@app.route('/hello/<int:id>')
  def hello(id):
    # so fastapi does the
    # control and conversion
    # automatically
    return f'Hello, {id**2}!'

Tip #3: return types

to shorten the code, the return type of a route implies automatic processing
we hardly need to convert objects to dict/json
especially if we use Pydantic models (we’ll talk about it again...)

Route returnHTTP response
dict or list or int or floatAutomatically encoded in JSON.
strSent as raw text (text/plain)
Pydantic BaseModelJSON automatically.
Example: return Item(name="Apple", price=1.5)
{"name":"Apple","price":1.5}

Tip #4: httpie