Libraries: fastapi Flashcards

(19 cards)

1
Q

Run main.py in development mode

A

fastapi dev main.py

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Create FastAPI app

A

app = FastAPI()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to define path parameters?

Define get endpoint accepting id in URL

A

Path paramters: define them in path like variables in format string, accept them in argument list (same name).

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to define query parameters

A

Query paramters: when you declare other function parameters that are not part of the path parameters, they are automatically interpreted as “query” parameters.

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip: skip + limit]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to limit path parameters to predefined set of values

A

Use enum to define parameter model.

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  • How to validate path or query parameter.
  • What validation options are available
A

Annotated[int, Path(<<VALIDATION OPTIONS>>)]

Can be also used for Query(), Body(), Header(), and Cookie()

Validation is same as pydantic fields.

@app.get("/items/{item_id}")
async def read_items(item_id: Annotated[int, Path(title="The ID of the item to get")]):
    results = {"item_id": item_id}
    return results
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to define common set of query parameters (to be shared by multiple endpoints)

A

FastAPI will extract the data for each field from the query parameters in the request and give you the Pydantic model you defined.

Use Query Parameter Models.

class FilterParams(BaseModel):
    tags: list[str] = []
		
@app.get("/items/")
async def read_items(filter_query: Annotated[FilterParams, Query()]):
    return filter_query
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to define request body

A

To declare a request body, you use Pydantic models.

class Item(BaseModel):
    name: str

@app.post("/items/")
async def create_item(item: Item):
    pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Define POST endpoint /items

A

@app.post("/items/")

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Define GET endpoint /items with "items" tag, short and long description of it.

A
@app.get("/items",
         tags=["items"], # they will define sections in Swagger UI
         summary="Short",
         description="More descriptive"
				 )
async def read_items():
    pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to return HTTP 404 error

A

Throw HTTPException

    raise HTTPException(
        status_code=404,
        detail="Item not found",
        headers={"X-Error": "There goes my error"},
    )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Read cookie named ads_id

A
@app.get("/items/")
async def read_items(ads_id: Annotated[str | None, Cookie()] = None):
    return {"ads_id": ads_id}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Define set of possible cookies that endpoint can accept

A
class Cookies(BaseModel):
    # Forbid Extra
    model_config = {"extra": "forbid"}
    session_id: str
    fatebook_tracker: str | None = None
    googall_tracker: str | None = None

@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
  return cookies
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Read User-Agent heade rin endpoint

A
@app.get("/items/")
async def read_items(user_agent: Annotated[str | None, Header()] = None):
  return {"User-Agent": user_agent}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Respond with status code 201 on success from an endpoint

A
@app.post("/items/", status_code=201)
async def create_item(name: str):
    return {"name": name}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Accept form fields for username and password

A

Required: pip install python-multipart

@app.post("/login/")
async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
    return {"username": username}
17
Q

How to define path dependencies

A

Dependency should be a "callable". You can use a Python class as a dependency.

# Define Dependency
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
  return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
  return commons

Using class

class CommonQueryParams:
  def \_\_init\_\_(self, q: str | None = None, skip: int = 0, limit: int = 100):
    self.q = q
    self.skip = skip
    self.limit = limit

async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]):
  # commons: Annotated[CommonQueryParams, Depends()] # shortcut
  pass
18
Q

How to add CORS support

A
app.add_middleware(
  CORSMiddleware,
  allow_origins=origins,
  allow_credentials=True,
  allow_methods=["*"],
  allow_headers=["*"],
)
19
Q

How to test FastAPI apps

A

Use TestClient based on httpx (similar API to requests)

from fastapi.testclient import TestClient

from .main import app

client = TestClient(app)

def test_read_item():
    response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})