EPAM Python + FastAPI Interview Questions & Answers
What are Python's data types and how is memory managed?
Python has various built-in data types like int, float, str, list, tuple, dict, set. Memory is managed using reference counting
and a cyclic garbage collector.
Difference between `is` and `==`?
`is` checks identity (memory address), while `==` checks equality of value.
How do you handle memory leaks in Python?
By monitoring object references, using weakref module, and profiling tools like objgraph.
Explain list comprehension with example.
List comprehension is a concise way to create lists. Example: `[x*x for x in range(5)]`
How is multithreading different from multiprocessing in Python?
Multithreading runs threads in the same memory space (subject to GIL), multiprocessing runs in separate memory
spaces.
What are Python decorators?
Decorators are functions that modify the behavior of other functions. Example: `@login_required`.
Explain Python generators and `yield`.
Generators produce items one at a time using `yield`, useful for memory-efficient iteration.
What is GIL (Global Interpreter Lock)?
GIL is a mutex that allows only one thread to execute Python bytecode at a time.
EPAM Python + FastAPI Interview Questions & Answers
What are dunder/magic methods?
Special methods with double underscores like `__init__`, `__str__`, `__repr__`.
How is inheritance handled in Python?
Python supports single, multiple, multilevel inheritance using classes.
Difference between `@staticmethod`, `@classmethod`, and instance methods?
`@staticmethod` has no access to class/instance, `@classmethod` gets class as `cls`, instance methods get `self`.
Explain `super()` with example.
`super()` calls parent class methods. Example: `super().__init__()` in child class.
What is FastAPI and how is it different from Flask or Django?
FastAPI is an async web framework. Its faster than Flask and more modern than Django for APIs.
How does FastAPI achieve asynchronous programming?
By using Python's async/await with ASGI servers like Uvicorn.
How do you handle request validation in FastAPI?
Using Pydantic models to define expected input data with validation.
Explain Pydantic and its role in FastAPI.
Pydantic is used for data parsing, validation and serialization in FastAPI.
How do you implement middleware in FastAPI?
EPAM Python + FastAPI Interview Questions & Answers
Using `@[Link]('http')` to define a function that runs before/after requests.
How do you write unit tests for FastAPI endpoints?
Using `TestClient` from FastAPI and `pytest` to simulate HTTP calls.
How do you structure a large FastAPI application?
Split into routers, services, models, and schemas. Use APIRouter and Dependency Injection.
How to use dependency injection (`Depends`) in FastAPI?
`Depends` is used to inject shared logic, like auth or DB session, into endpoints.
How can you secure FastAPI APIs? (OAuth2, JWT)
Use OAuth2PasswordBearer with JWT tokens, and secure routes with `Depends`.
What are background tasks in FastAPI? Give use cases.
Tasks that run after response is returned. Use `BackgroundTasks`. Example: send emails.
Write a FastAPI route that receives a list of numbers and returns their sum.
```python
@[Link]('/sum')
def get_sum(nums: List[int]):
return {'total': sum(nums)}
```
Create a FastAPI route with path params and query params.
EPAM Python + FastAPI Interview Questions & Answers
```python
@[Link]('/items/{item_id}')
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
Write a decorator in Python that logs execution time.
```python
import time
def timer(func):
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
print([Link]() - start)
return result
return wrapper
```
Given a string, write a function to find the first non-repeating character.
```python
def first_unique(s):
from collections import Counter
count = Counter(s)
for c in s:
if count[c] == 1:
EPAM Python + FastAPI Interview Questions & Answers
return c
return None
```
Build a FastAPI CRUD service for a simple `Todo` model.
Use Pydantic for schemas, SQLAlchemy/Tortoise for DB, and define routes for create/read/update/delete.
How to paginate results in FastAPI? Write a sample API.
```python
@[Link]('/items')
def get_items(skip: int = 0, limit: int = 10):
return db[skip:skip+limit]
```
How would you consume a third-party API inside FastAPI?
Using `httpx` or `requests` in an async or sync manner depending on endpoint.
How do you implement file upload/download in FastAPI?
Use `File` and `UploadFile` for uploads, and `FileResponse` for downloads.
How do you return a custom JSON error response globally?
Use `app.exception_handler()` to define custom error formats.
How to connect PostgreSQL with FastAPI?
Use SQLAlchemy or Tortoise ORM with async drivers like asyncpg.
EPAM Python + FastAPI Interview Questions & Answers
Explain async SQLAlchemy and how its used in FastAPI.
Use `async_session` and `await` for DB operations.
How do you handle transactions and rollbacks?
Use [Link]() or `async with [Link]()` to ensure rollback on error.
What is Alembic and how to use it with FastAPI?
Alembic is used for DB migrations. Use `alembic init` and version files.
How to deploy FastAPI using Gunicorn and Uvicorn?
Use command: `gunicorn app:app -k [Link]`
How do you containerize a FastAPI app with Docker?
Create a Dockerfile with FastAPI, expose port 8000, and run via uvicorn.
Explain your experience with CI/CD tools (GitHub Actions, Jenkins).
Set up pipeline to run tests, lint code, build image, and deploy.
How to use environment variables securely in FastAPI?
Use `python-dotenv` or `[Link]` with `.env` file.
How would you design a high-performance API with FastAPI for 10,000 users per second?
Use async, caching (Redis), efficient DB queries, and horizontal scaling.
When to use async vs sync endpoints in FastAPI?
EPAM Python + FastAPI Interview Questions & Answers
Use async when doing IO-bound tasks (DB/API), sync for CPU-bound.
How do you design microservices using FastAPI?
Separate services, use message broker (like RabbitMQ), and service registry.
Suppose a FastAPI endpoint is slow how would you debug and optimize it?
Profile with `cProfile`, optimize DB queries, and add caching.
How do you handle versioning in FastAPI?
Use path prefixes like `/v1/api`, `/v2/api` in router definitions.
How do you test database-related code in FastAPI?
Use `TestClient` with test DB, or use `SQLAlchemy` with `rollback()` after each test.