Python Interview Questions: APIs, Boto3, Data (2027)

Python interview questions on requests, FastAPI, boto3, pandas, pytest and concurrency, with working code, checked against current official docs.

Sep 6, 2025 - 10:54
Nov 9, 2026 - 13:04
 0  56
Python Interview Questions: APIs, Boto3, Data (2027)

Python interviews for IT, data and DevOps roles often move past syntax to the libraries you use at work: requests for HTTP calls, Flask or FastAPI for services, boto3 for AWS automation, pandas for data cleaning, pytest for tests and threads or asyncio for concurrency. This page gives 32 direct answers with short, working code.

Language basics, internals and coding drills are covered in other guides: start with the Python preparation guide, the internals guide and the scenario-based Python questions. This page focuses on libraries and tooling. Library versions were checked against PyPI and official documentation in November 2026 (for example boto3 1.44, pandas 3.1, FastAPI 0.162, pytest 9.2 and requests 2.34). Practise these alongside the scripting work in our DevOps training in Pune.

Key takeaways

  • Every network call needs a timeout. requests has no default timeout, so a missing one is a classic review comment.
  • boto3 clients are thread-safe but cannot be shared across processes. Resources and sessions are not thread-safe, so create a session per thread.
  • pandas 3.0 turned on Copy-on-Write and a dedicated string dtype by default. Chained assignment no longer modifies the original object.
  • Use threads or asyncio for I/O-bound work, processes for CPU-bound work. Free-threaded Python is officially supported from Python 3.14.
  • Python 3.10 reached end of life on 1 October 2026. Python 3.11 to 3.15 are the supported branches.
  • Show tests with your code. A short pytest example with a fixture and a mock earns more trust than a long explanation.

What this page covers

AreaTypical interview angleQuestions
Environments and packagingIsolation, dependencies, secrets1 to 5
HTTP and web servicesrequests, Flask, FastAPI6 to 12
AWS automation with boto3Clients, pagination, errors, threads13 to 19
Data work with pandasCleaning, joins, memory, version changes20 to 24
Testing and loggingpytest, mocks, structured logs25 to 28
ConcurrencyThreads, asyncio, processes29 to 32

Environments and packaging

1. Why use a virtual environment?

A virtual environment holds a specific interpreter and the libraries one project needs, isolated from the system Python and from other projects. Create one with python -m venv .venv, activate it, and install with pip. Without it, two projects needing different versions of a library will conflict.

2. How do you make installs reproducible?

Pin versions in a lock or requirements file, and keep project metadata in pyproject.toml. Install from that file in CI so every environment gets the same versions. Re-run tests when you update pins.

3. How do you keep secrets out of code?

Read them from environment variables or a secret manager at runtime, never commit them, and use os.environ["NAME"] so a missing value fails loudly instead of using a default. Rotate anything that was ever committed.

4. Which Python versions should a new project target?

A supported one. According to the Python developer guide, 3.10 reached end of life on 1 October 2026, and 3.11 through 3.15 are still supported. Pick the oldest version your deployment platform supports, and test on the newest.

5. What changed in Python 3.14 that interviewers mention?

Python 3.14 added template string literals (t-strings), deferred evaluation of annotations and subinterpreter support in the standard library, and made free-threaded Python officially supported under PEP 779. You only need a one-line explanation of each.

HTTP and web services

6. What is wrong with requests.get(url) in production code?

It has no timeout, so a stalled server can block your program forever, and it ignores HTTP error status unless you check. Set a timeout and call raise_for_status().

import requests

resp = requests.get("https://api.example.com/items", timeout=5)
resp.raise_for_status()
items = resp.json()

7. How do you add retries to HTTP calls?

Mount an adapter with a retry policy on a Session, so transient errors such as 502 and 503 are retried with backoff.

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=3, backoff_factor=0.5, status_forcelist=[502, 503, 504])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
resp = session.get("https://api.example.com/items", timeout=5)

8. Why use a Session?

A Session reuses connections, so repeated calls to one host avoid new TCP and TLS handshakes, and it keeps headers, cookies and adapters in one place.

9. How do you write a small JSON API in FastAPI?

Declare a Pydantic model for the request body and a function for the route. FastAPI validates input and produces OpenAPI documentation automatically.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
def create_item(item: Item):
    return {"name": item.name, "price": item.price}

Run it with uvicorn main:app --reload during development.

10. When would you choose Flask over FastAPI, or the other way round?

Flask is minimal and fits small services and teams that already have Flask extensions. FastAPI fits services where typed request validation, async support and generated API documentation matter. Either is a fair answer if you explain the trade-off.

11. How do you handle blocking calls in an async endpoint?

Do not call blocking code inside async def, because it blocks the event loop for every request. Use an async client library, or define the endpoint with plain def so it runs in a thread pool, or push the work to a background worker.

12. How do you version and test an API?

Prefix routes with a version such as /v1, keep contracts in the Pydantic models, and test with the framework's test client against the app object without starting a server.

AWS automation with boto3

13. What is the difference between a boto3 client and a resource?

A client is the low-level interface that maps closely to AWS API operations and returns dictionaries. A resource is a higher-level object interface for some services. Clients are generally thread-safe and resources are not.

14. How does boto3 find credentials?

It searches a chain that includes environment variables, shared credential and config files, and role-based sources such as an instance or container role. In code, create the client without keys and let the chain work, so the same script runs locally and on AWS.

15. How do you list all objects in a large bucket?

Use a paginator, because a single call returns a limited page.

import boto3

s3 = boto3.client("s3")
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket="my-bucket", Prefix="logs/"):
    for obj in page.get("Contents", []):
        print(obj["Key"])

16. How do you handle AWS errors?

Catch botocore.exceptions.ClientError and read the code from e.response["Error"]["Code"]. Handle expected codes such as a missing key explicitly, and let unexpected ones propagate.

from botocore.exceptions import ClientError

try:
    s3.head_object(Bucket="my-bucket", Key="a.txt")
except ClientError as e:
    if e.response["Error"]["Code"] == "404":
        print("missing")
    else:
        raise

17. Is boto3 safe to use with threads and processes?

Clients are generally thread-safe, but you should not share a client across processes. Resources and sessions are not thread-safe. The documented pattern is to create a session in each thread and a client from it, and not to call boto3.client() inside a concurrent context because it uses a shared default session.

18. How would you write a script that tags untagged EC2 instances?

Paginate describe_instances, filter for instances missing the tag, call create_tags in batches, log what changed, and support a dry-run flag so you can review the list first. Many DevOps interviews expect this shape. See Python scripts for DevOps automation for more.

19. How do you test code that calls AWS?

Wrap AWS calls in a small function, and in tests replace the client with a stub or mock so no real account is touched. Keep one integration test in a sandbox account for the real behavior.

Data work with pandas

20. What changed in pandas 3.0?

A dedicated string dtype is now the default for text columns instead of object, and Copy-on-Write behavior is on, so any indexing result behaves like a copy. Code that checks dtype == object for strings, or relies on chained assignment to modify a DataFrame, must be updated.

21. Why does this no longer change the DataFrame?

With Copy-on-Write, df[df["a"] > 1]["b"] = 0 modifies a temporary result. Write the update in one step with df.loc[df["a"] > 1, "b"] = 0.

22. How do you process a CSV that does not fit in memory?

Read it in chunks with read_csv(..., chunksize=100000), aggregate each chunk, then combine the results. Also select only needed columns with usecols and set smaller dtypes.

23. What is the difference between merge and concat?

merge joins on keys like a SQL join, with options for inner, left, right and outer. concat stacks frames along an axis. Check for duplicate keys after a merge because they multiply rows.

24. How do you find and handle missing values?

Use df.isna().sum() to count them, then decide per column: drop rows, fill with a constant or statistic, or leave and handle downstream. Say why, because the right choice depends on what the column means.

Testing and logging

25. What do you cover in a pytest answer?

Plain assert statements, fixtures for setup, parametrize for many inputs, and monkeypatch or mocks for isolation.

import pytest

@pytest.mark.parametrize("a,b,total", [(1, 2, 3), (0, 0, 0)])
def test_add(a, b, total):
    assert a + b == total

26. How do you mock an HTTP call?

Patch the function that makes the call where it is used, using unittest.mock.patch or monkeypatch, and return a fake response. Assert both the result and that the call was made with the expected arguments.

27. Why use logging instead of print?

The logging module gives levels, timestamps, handlers and a way to change verbosity without editing code. In services, emit one structured line per event so log tools can filter by field.

28. What makes a script safe to run in CI?

It returns a non-zero exit code on failure, writes errors to stderr, reads configuration from arguments or environment variables, and does not prompt for input.

Concurrency

29. Threads, asyncio or processes?

Use threads or asyncio when work waits on I/O, such as HTTP or AWS calls. Use processes for CPU-bound work because of the global interpreter lock in the standard build. Free-threaded builds, officially supported from Python 3.14, change that trade-off but are not the default.

30. How do you call 100 URLs concurrently?

Use a thread pool for blocking libraries or an async client with asyncio.gather. Limit concurrency so you do not overwhelm the target server or hit rate limits.

from concurrent.futures import ThreadPoolExecutor
import requests

def fetch(url):
    return requests.get(url, timeout=5).status_code

with ThreadPoolExecutor(max_workers=10) as pool:
    codes = list(pool.map(fetch, urls))

31. What is a race condition and how do you avoid it in Python?

Two threads change shared state in an unsafe order. Avoid shared mutable state, pass data through queues, or protect critical sections with a lock.

32. What goes wrong with asyncio in practice?

Blocking calls inside coroutines, forgotten await, and unbounded task creation. Use timeouts and a semaphore to bound concurrency.

How to practise

  1. Write a script that lists S3 objects with a paginator and a dry-run flag.
  2. Wrap a public API with a retrying Session, then test it with a mock.
  3. Expose it with a FastAPI route and a Pydantic model.
  4. Load a large CSV in chunks and report missing values.

For harder coding rounds read the scenario questions, then the 15 DevOps task automations in Python.

Frequently asked questions

Which Python libraries are asked most in DevOps and cloud interviews?

requests for HTTP, boto3 for AWS, a web framework such as Flask or FastAPI, pandas for data work, pytest for tests, and logging.

Does requests have a default timeout?

No. You must pass a timeout argument, otherwise a call can wait indefinitely.

Are boto3 clients thread-safe?

Clients are generally thread-safe but cannot be shared across processes. Resources and sessions are not thread-safe, so create a session per thread.

What changed in pandas 3.0?

Copy-on-Write and a dedicated string dtype became the defaults, and many deprecated features were removed.

Which Python versions are supported?

According to the Python developer guide, 3.11 to 3.15 are supported and 3.10 reached end of life on 1 October 2026.

Should I learn Flask or FastAPI?

Learn one well and know the trade-offs of the other. FastAPI is common for new typed APIs, and Flask is common in existing services.

Official references

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.