FastAPI Flashcards

(72 cards)

1
Q

What FastAPI uses behind the scenes to check type validation?

A

Pydantic

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

What is an Enum in FastAPI?

A

An Enum in FastAPI is a symbolic name for a set of values, which can be used to define a limited set of valid options for parameters.

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

True or False: Enums can be used in FastAPI path parameters to enforce valid input values.

A

True

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

Fill in the blank: Enums in FastAPI can be defined using the _______ module from the Python standard library.

A

enum

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

Which of the following is a valid way to define an Enum in FastAPI? A) class MyEnum(Enum): A = ‘value1’ B) my_enum = Enum(‘MyEnum’, ‘value1 value2’) C) Both A and B

A

C

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

How do you specify an Enum as a path parameter in FastAPI?

A

By using the Enum type as the type hint for the path parameter in the route function.

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

What HTTP status code indicates a successful request in FastAPI?

A

200 OK

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

True or False: In FastAPI, you can set a custom status code in the response using the ‘status_code’ parameter.

A

True

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

Fill in the blank: To return a ‘404 Not Found’ status in FastAPI, you can use the response model and set the status code with ______.

A

status.HTTP_404_NOT_FOUND

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

Which FastAPI function is used to create a response with a specific status code?

A

JSONResponse

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

What is the correct way to return a ‘201 Created’ status when creating a new resource in FastAPI?

A

return JSONResponse(content={‘message’: ‘Resource created’}, status_code=status.HTTP_201_CREATED)

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

What is the primary purpose of tags in FastAPI?

A

To group and organize API endpoints for better documentation and usability.

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

True or False: Tags in FastAPI can only be applied to functions and not to classes.

A

False

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

Fill in the blank: In FastAPI, you can assign tags to an endpoint using the ______ parameter.

A

tags

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

Which of the following is a correct way to define tags for an endpoint in FastAPI?
A) tags=[‘user’]
B) tag=’user’
C) tags=’user’
D) tag=[‘user’]

A

A) tags=[‘user’]

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

What effect do tags have on the generated OpenAPI documentation in FastAPI?

A

Tags help organize the endpoints into sections, making the documentation clearer and easier to navigate.

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

What is FastAPI primarily used for?

A

FastAPI is primarily used for building APIs with Python.

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

True or False: FastAPI automatically validates request and response data.

A

True

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

Fill in the blank: FastAPI is based on __________ and uses standard Python type hints.

A

Starlette

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

Which feature of FastAPI helps in automatic generation of API documentation?

A

OpenAPI

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

What is the primary benefit of using FastAPI over other frameworks?

A

FastAPI offers high performance and easy-to-use features like automatic data validation and interactive documentation.

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

What is the purpose of the summary feature in FastAPI?

A

The summary feature provides a brief description of the endpoint’s functionality in the generated API documentation.

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

True or False: The description feature in FastAPI can be used to provide detailed information about an endpoint.

A

True

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

Fill in the blank: In FastAPI, the summary and description can be added to an endpoint using the parameters ______ and ______.

A

summary, description

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Which of the following is NOT a benefit of using summary and description features in FastAPI? A) Improved documentation B) Enhanced security C) Clearer API understanding D) Better usability
B) Enhanced security
26
What type of information is typically included in the description feature of a FastAPI endpoint?
Detailed information about the endpoint's purpose, usage, and any relevant details for users.
27
What is the primary purpose of routers in FastAPI?
To define and organize the application's endpoints and their associated HTTP methods.
28
True or False: In FastAPI, routers can be used to group related routes together.
True
29
Fill in the blank: In FastAPI, a router is an instance of the ______ class.
APIRouter
30
Which method is used to include a router in a FastAPI application?
app.include_router()
31
What is a key benefit of using routers in FastAPI for large applications?
They help in organizing code into modular components, making it easier to manage and maintain.
32
What is parameter metadata in FastAPI used for?
It is used to define additional information about parameters in API endpoints.
33
True or False: Parameter metadata can include descriptions, examples, and default values.
True
34
Fill in the blank: In FastAPI, parameter metadata can be specified using the _______ function.
Query
35
Which of the following is NOT a type of parameter metadata in FastAPI? A) description B) example C) validation D) response
D) response
36
What is the purpose of using the 'title' attribute in parameter metadata?
It provides a human-readable name for the parameter in the generated documentation.
37
What is the primary purpose of validators in FastAPI?
To ensure that the data received in requests meets specified criteria before processing.
38
True or False: FastAPI uses Pydantic for data validation.
True
39
Fill in the blank: In FastAPI, a _______ is a class used to define the structure and validation rules for request data.
Pydantic model ex. from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_available: bool = True # Default value @app.post("/items/") async def create_item(item: Item): return item
40
Which of the following is NOT a type of validation provided by FastAPI? (A) Length validation, (B) Regex validation, (C) SQL injection prevention
C
41
What method is used to validate a request body in FastAPI?
By declaring a Pydantic model as a parameter in the path operation function.
42
How to define queryparams in FastAPI with optional default values to get www.example.com?id=1&id=2&id=3
id: Optional[List[str]] = Query(['1', '2', '3'])
43
How in FastAPI define the value that can be only greater than 5 and less than 10?
value: int = Path(None, gt=5, le=10)
44
What is the same thing as typescript but in Python
Type hints & type annotation
45
Give an example of type hints and type annotations
def greet(name: str) -> str: # 'name: str' is a type annotation return f"Hello, {name}!" age: int = 30 # 'age: int' is a type annotation result = greet("Alice") # 'result' is inferred to be of type 'str'
46
What are type hint?
A type hint is a suggestion to the type checker about what type a variable or function parameter should be. It does not enforce type checking at runtime but provides information to developers and tools (like IDEs and static analyzers) about the expected types.
47
What are type annotations?
A type annotation is the actual syntax used to provide type hints in the code. It involves using a colon (:) followed by the type after the variable name or function parameter. For function return types, the annotation is placed after the -> symbol.
48
What is mypy?
mypy is a static type checker for Python that analyzes the code and checks the type hints for consistency. It helps identify type-related errors without executing the code.
49
mypy vs type hint & type annotations
Type hints and type annotations in Python provide a way to specify expected types, but they do not enforce type checking at runtime. This means that even with type hints, you can still write code that has type-related errors that won't be caught until runtime.
50
What is a dependency in FastAPI?
In FastAPI, a dependency is a way to define reusable components that can be injected into your route handlers (endpoints). Dependencies allow you to encapsulate common logic, such as authentication, database connections, or any other functionality that you want to share across multiple routes. A simple dependency function def get_query_param(q: str = None): if q: return q raise HTTPException(status_code=400, detail="Query parameter 'q' is required") @app.get("/items/") async def read_items(q: str = Depends(get_query_param)): return {"query": q}
51
Schema vs Models in FastAPI
Schema refers to a Pydantic model that defines the structure and validation rules for incoming data from users A model in this context typically refers to an ORM (Object-Relational Mapping) model that represents the structure of a database table. This model defines how data is stored in the database and may include relationships with other tables.
52
Give an example of FastAPI Schema
class UserCreateSchema(BaseModel): username: str email: str password: str
53
Give an example of FastAPI Model
class UserModel(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True) email = Column(String, unique=True, index=True) password = Column(String)
54
Why we need db.refresh(new_user) here?
This ensures that any fields automatically set by the database (like autogenerated IDs, timestamps, or default values) are updated in your Python object before you return it. Without db.refresh(new_user), those fields might remain unset or outdated in the returned object after db.commit().
55
Why yield instead of return?
yield is used instead of return in FastAPI dependencies like get_db() to allow for cleanup actions after the request is handled. When you use yield, FastAPI injects the database session into your endpoint, and after the response is sent, the code after yield (such as db.close()) runs automatically to close the session.
56
How to get all elements from DbUser table?
db.query(DbUser).all()
57
How to get one element from DbUser table?
db.query(DbUser).filter(DbUser.id == id).first()
58
def get_user(id: int, db: Session = Depends(get_db)) Why we need Depends there, why not just db: Session = get_db()
If you write db: Session = get_db(), Python will call get_db() once at startup, not per request. This means: - The same DB session (or generator) is shared across all requests (very bad!). - Resource cleanup (e.g., closing the session) won’t work as intended. - You lose all the benefits of FastAPI’s dependency system.
59
How to create custom exception?
class MyCustomException(Exception): def __init__(self, name: str): self.name = name
60
How to Create a Custom Exception Handler?
@app.exception_handler(MyCustomException) async def my_custom_exception_handler(request: Request, exc: MyCustomException): return JSONResponse( status_code=418, content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, )
61
How to return response body of type text/html
return HTMLResponse(content=out, media_type="text/html")
62
How to return response body of type text/plain
return PlainTextResponse(content=out, media_type="text/plain")
63
How to document in fastapi that our endpoint on 200 has text/html and on 404 text/plain?
@app.get( "/my-endpoint", responses={ 200: { "description": "Successful HTML response", "content": { "text/html": { "example": "

Hello, World!

" } }, }, 404: { "description": "Not Found as plain text", "content": { "text/plain": { "example": "Not found" } }, }, }, )
64
How to add single header in request function definition?
65
How to add header with multiple values in request function definition?
66
How to provide custom header in response?
67
What can cookie accept as a value in FastApi?
68
How to set cookie on response in FastAPI?
69
How to setup CORS in FastAPI?
70
What "..." means in File(...) in FastAPI?
Required vs. Optional: The ellipsis (...) inside File(...) means the file is required. You can make it optional by providing a default value, e.g., File(default=None)
71
How to upload file in the repository in the simple manner in FastAPI?
72
How to allow the web to see our static files placed in "/files" folder from our FastAPI server?