0% found this document useful (0 votes)
18 views10 pages

Python API Developer Interview Questions

Uploaded by

rohitd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

Python API Developer Interview Questions

Uploaded by

rohitd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Fresher Backend API Developer – Interview Question Bank

Section A: Python Basics & Problem Solving

1. What are the main built-in data types you use in Python for backend work?
Common ones are:

- int, float – numeric values


- str – text
- list – ordered, mutable collection
- tuple – ordered, immutable collection
- set – unordered collection of unique items
- dict – key–value mapping (hash map)
- bool – True/False values

For APIs, dicts and lists are used a lot when handling JSON payloads.

2. What is the difference between a list and a tuple?


• Mutability:
- List: mutable (can add/remove/modify elements).
- Tuple: immutable (cannot be changed after creation).
• Use cases:
- List: when the collection can change (e.g., items in a cart).
- Tuple: when you want a fixed group (e.g., coordinates, or returning multiple values from a
function).

3. How would you swap two variables in Python?


Answer:
a, b = b, a
This uses tuple unpacking, no temporary variable required.

4. What is the difference between == and is?


• '==' checks value equality (do they look equal?).
• 'is' checks identity (are they the same object in memory?).

Example:
a = [1, 2]
b = [1, 2]
a == b # True
a is b # False

5. How do you handle exceptions in Python?


Using try / except (optionally else and finally):

try:
result = 10 / x
except ZeroDivisionError:
result = None
else:
print("No error occurred")
finally:
print("This always runs")

6. What is a virtual environment and why is it important?


A virtual environment is an isolated Python environment with its own installed packages,
separate from the global Python installation.

• Prevents dependency conflicts between projects.


• Keeps project requirements clean and reproducible.

Typically created with:


python -m venv venv
source venv/bin/activate (Linux/Mac)
venv\Scripts\activate (Windows)

7. Coding: Given a list of integers, return a new list with only the even numbers.
def filter_even(nums):
return [n for n in nums if n % 2 == 0]

8. Coding: Check if a string is a palindrome (ignore case and spaces).


def is_palindrome(s: str) -> bool:
cleaned = "".join([Link]() for ch in s if [Link]())
return cleaned == cleaned[::-1]
9. What is list comprehension? Rewrite a basic loop using it.
List comprehension is a concise way to create lists.

Loop:
result = []
for x in range(5):
[Link](x * x)

List comprehension:
result = [x * x for x in range(5)]

10. What is the time complexity of searching for an element in a list vs in a set?
• List: O(n) – need to scan elements one by one.
• Set: Average O(1) – uses a hash table internally.

11. How would you remove duplicates from a list while keeping the original order?
def remove_duplicates(nums):
seen = set()
result = []
for n in nums:
if n not in seen:
[Link](n)
[Link](n)
return result

12. Explain the concept of mutable vs immutable types with an example.


• Immutable: Cannot be changed in place (e.g. int, str, tuple).
Example: s = "abc"; s[0] = "x" -> error.
• Mutable: Can be modified in place (e.g. list, dict, set).
Example:
a = [1, 2, 3]
[Link](4) # modifies list in place

13. How would you read a JSON request body in Python (not specific to any framework)?
Assuming you have a JSON string:
import json

json_str = '{"name": "Alice", "age": 25}'


data = [Link](json_str)
# data is now a Python dict

14. What is the difference between a function and a method?


• Function: A standalone block of code defined with 'def'.
Example: def add(a, b): ...
• Method: A function that belongs to an object/class.
Example:
class User:
def greet(self): ...

15. Coding: Write a function to count how many times each word appears in a string.
def word_count(text: str) -> dict:
counts = {}
for word in [Link]():
word = [Link]()
counts[word] = [Link](word, 0) + 1
return counts

Section B: API & Flask Knowledge

16. What is an API?


An API (Application Programming Interface) is a way for different software components to
communicate.
In web development, a web API is usually a set of HTTP endpoints through which clients
(browser, mobile app, other services) can send requests and get responses (often JSON).

17. What is a RESTful API?


A RESTful API follows REST principles:
• Uses standard HTTP methods (GET, POST, PUT, PATCH, DELETE).
• Resources identified by URLs (e.g. /users/1).
• Stateless: server doesn’t store client session between requests.
• Uses standard status codes and often JSON representations.

18. Name some common HTTP methods and their typical use in REST.
• GET – Retrieve data (read).
• POST – Create new resource.
• PUT – Replace an existing resource (full update).
• PATCH – Partial update.
• DELETE – Remove a resource.

19. What are HTTP status codes? Give examples of 2xx, 4xx, and 5xx.
• 2xx (Success): 200 OK, 201 Created, 204 No Content
• 4xx (Client error): 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
• 5xx (Server error): 500 Internal Server Error, 503 Service Unavailable

20. How do you install Flask and create a minimal “Hello World” API?
Install:
pip install flask

Minimal app:
from flask import Flask

app = Flask(__name__)

@[Link]("/hello")
def hello():
return "Hello, World!"

if __name__ == "__main__":
[Link](debug=True)

21. How do you return JSON from a Flask endpoint?


from flask import Flask, jsonify

app = Flask(__name__)

@[Link]("/user")
def get_user():
user = {"id": 1, "name": "Alice"}
return jsonify(user), 200

jsonify converts dicts/lists to JSON and sets proper headers.


22. How do you access query parameters and JSON body in Flask?
from flask import request

# Query parameter: /search?q=test


@[Link]("/search")
def search():
q = [Link]("q")
return f"You searched for {q}"

# JSON body: POST with JSON


@[Link]("/users", methods=["POST"])
def create_user():
data = request.get_json()
name = [Link]("name")
return {"message": f"User {name} created"}, 201

23. How do you restrict an endpoint to only accept POST in Flask?


@[Link]("/submit", methods=["POST"])
def submit():
...

24. What are Flask Blueprints and why would you use them?
Blueprints help organize routes into modules (e.g., auth, users, products) instead of putting
everything in one file.
They allow:
• Cleaner structure for large apps.
• Reusable chunks of routes.

Basic usage:
from flask import Blueprint

users_bp = Blueprint("users", __name__)

@users_bp.route("/users")
def list_users():
...

app.register_blueprint(users_bp)
25. How do you handle errors globally in Flask (e.g., 404 or 500)?
Using error handlers:
@[Link](404)
def not_found(e):
return {"error": "Not found"}, 404

@[Link](500)
def server_error(e):
return {"error": "Internal server error"}, 500

26. How would you implement simple authentication (e.g., API key) in Flask?
One simple approach is checking a header in a decorator or before_request:

from flask import request, abort

@app.before_request
def check_api_key():
api_key = [Link]("X-API-Key")
if api_key != "my-secret-key":
abort(401)

For real apps, use more secure methods (JWT, OAuth, etc.).

27. How do you connect Flask to a database conceptually (you don’t need full code)?
Conceptually:
• Install the database driver or ORM (e.g., psycopg2, SQLAlchemy).
• Configure connection settings (host, port, username, password, db name) in Flask config.
• Initialize the DB client/ORM with the Flask app.
• In routes, use the DB session/connection to query or update data.
• Handle connection cleanup (e.g., teardown_appcontext).

28. What is CORS and how would you enable it for a Flask API?
CORS (Cross-Origin Resource Sharing) controls browser requests from different origins
(e.g., [Link] calling [Link]).

In Flask:
pip install flask-cors

from flask import Flask


from flask_cors import CORS

app = Flask(__name__)
CORS(app) # allows all origins by default

29. How do you structure a Flask project for a medium-sized API?


Typical structure:
project/
[Link] # entry point
[Link] # configuration
[Link]
/app
__init__.py # create_app, register blueprints
/routes
[Link]
[Link]
/models
[Link]
/services
user_service.py

Use blueprints, separate modules for routes, models, services, and config for settings.

Section C: API Gateway Concepts

30. What is an API Gateway?


An API Gateway is a component that sits in front of backend services and acts as a single
entry point for clients.

It can:
• Route requests to the correct microservice.
• Handle authentication / authorization.
• Do rate limiting and throttling.
• Perform request/response transformation.
• Add logging, monitoring, and caching.

31. Why would you use an API Gateway instead of calling services directly?
• Single endpoint for clients instead of many service URLs.
• Centralized authentication & authorization.
• Rate limiting to protect backends.
• Request/response transformation so internal APIs can differ from public ones.
• Versioning and routing control without changing clients.
• Observability: logging, metrics, tracing at a single layer.

32. How does an API Gateway work with a Flask backend?


Client → API Gateway → Flask service.

• Gateway maps an incoming path/method (e.g., GET /users) to the Flask service endpoint
(e.g., [Link]
• Gateway may:
- Validate tokens / API keys before forwarding.
- Add headers (like user identity).
- Transform payloads if needed.

Flask app itself doesn’t know about the gateway; it just sees normal HTTP requests.

33. What is rate limiting and why is it important at the API Gateway layer?
Rate limiting restricts how many requests a client can make in a given time period (e.g., 100
requests per minute).

• Protects backend services from being overloaded.


• Prevents abuse or brute force attacks.
• Helps ensure fair usage among clients.

API Gateways commonly support built-in rate limiting configurations.

34. How can an API Gateway help with API versioning?


• You can expose multiple versions (e.g., /v1/users, /v2/users) via the gateway.
• The gateway routes each version to different backend services or routes.
• Lets you gradually migrate clients from old to new versions without breaking existing
ones.

35. What is request/response transformation in an API Gateway?


It’s the ability of the gateway to modify incoming requests or outgoing responses, for
example:
• Add/remove/rename headers.
• Change JSON structure (rename fields, wrap or unwrap payloads).
• Convert between formats (e.g., XML to JSON).

This allows backend services to evolve internally without forcing client changes.

You might also like