-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
43 lines (30 loc) · 1.2 KB
/
main.py
File metadata and controls
43 lines (30 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import json
from dataclasses import dataclass, field
from fastapi import FastAPI, HTTPException, Response, status
app = FastAPI()
@dataclass
class Channel:
id: str
name: str
tags: list[str] = field(default_factory=list)
description: str = ""
# channels is a `dict` where keys are `str` and values are `Channel` object
channels: dict[str, Channel] = {}
with open("channels.json", "r", encoding="utf8") as file:
# encoding="utf8" avoids unicode issues (if there is some encoding data)
channels_raw: list[dict] = json.load(file) # load json data to dict
for channel_raw in channels_raw:
# it creates a `Channel` object by mapping dict keys to constructor \
# arguments
channel = Channel(**channel_raw)
channels[channel.id] = channel
# server health check
@app.get('/')
def read_root():
return Response(content="The server is running.")
@app.get("/channels/{channel_id}", response_model=Channel)
def read_item(channel_id: str) -> Channel:
if channel_id not in channels:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Channel with id {channel_id} not found.")
return channels[channel_id]