Introduction
Application Programming Interfaces (APIs) allow different software components to communicate and work together seamlessly. Due to its simplicity, scalability, and versatility, REST APIs can handle diverse types of calls, return multiple data formats, and adapt structurally through the implementation of hypermedia. This makes them an invaluable tool in software development.
According to Statista, software developers spend an average of 30% of their time coding APIs. This statistic highlights the integral role of APIs in everyday coding tasks and shows their importance in creating interconnected, efficient digital solutions.
REST APIs play an important role in enabling interoperability and creating dynamic, responsive applications, making REST API knowledge essential for software developers. Understanding and effectively assessing these skills in candidates is crucial for hiring managers.
In this article, we will explain what a REST API is and provide the top 6 REST API coding questions aimed at testing a developer’s REST API expertise.
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a set of rules and conventions for building web services that enable different computer systems to communicate over the Internet. RESTful APIs use HTTP requests to access and manipulate data, utilizing a range of standard methods like GET, POST, PUT, and DELETE. These methods correspond to the fundamental actions of reading, creating, updating, and deleting (CRUD) in database management.
According to APIs for Dummies, since 2005, REST has been growing as one of the most popular API protocols. This growth shows its simplicity and how it leverages existing web technologies and protocols, such as HTTP. Using standard HTTP methods like GET, POST, PUT, and DELETE, REST APIs provide a familiar and straightforward way to perform operations on data.
According to Deloitte Research, 77% of companies with successful API management transformations translate their strategy into operational mechanisms, monitoring progress and making changes.
Popular companies that use REST APIs include:
- Google: Google utilizes REST APIs for a vast array of its services, including Google Maps, Google Drive, and YouTube, allowing developers to integrate these services into their own applications.
- Amazon: Amazon Web Services (AWS) offers numerous RESTful APIs, enabling developers to access the functionalities of AWS’s cloud computing solutions.
- Facebook: Facebook’s Graph API, a RESTful web service, allows developers to read and write data to and from the Facebook social graph.
- Twitter: Twitter provides a REST API for developers to interact with virtually all aspects of Twitter, including retrieving tweets, posting new tweets, and performing user management operations.
- Microsoft: Microsoft uses REST APIs extensively in its cloud services, including Azure and the Office 365 suite, facilitating integration and automation across its cloud offerings.
- Netflix: Netflix’s service-oriented architecture heavily relies on REST APIs for its internal services communication and external APIs consumed by various client applications.
REST APIs represent a standardized and efficient way for different applications to communicate over the Internet. They embody a set of guidelines that ensure the development of easy web services to understand, implement, and use, underpinning the interconnected nature of today’s digital landscape. REST APIs have become a fundamental part of the digital infrastructure, driving innovation and connectivity in the software industry.
Top 6 REST API Interview Questions
Let’s explore the top 6 REST API interview questions:
1. Create a Simple RESTful Service to Manage a To-Do List
Task | Create a Python function using the Flask framework to manage a simple to-do list. The API should support adding a new task, getting a list of all tasks, updating a task description, and deleting a task. |
Input Format | For adding a new task, the input should be a JSON object, for example, {“task”: “Buy groceries”}. |
Constraints |
|
Output Format | The output should be in JSON format. For fetching all tasks, it should resemble [{“id”: 1, “task”: “Buy groceries”}, {“id”: 2, “task”: “Read a book”}]. |
Suggested Answer
from flask import Flask, jsonify, request
app = Flask(__name__) tasks = [] task_id = 1 @app.route(‘/tasks’, methods=[‘GET’]) def get_tasks(): return jsonify(tasks) @app.route(‘/tasks’, methods=[‘POST’]) def add_task(): global task_id new_task = {“id”: task_id, “task”: request.json[‘task’]} tasks.append(new_task) task_id += 1 return jsonify(new_task), 201 @app.route(‘/tasks/<int:id>’, methods=[‘PUT’]) def update_task(id): task = next((item for item in tasks if item[‘id’] == id), None) if task is None: return jsonify({“error”: “Task not found”}), 404 task[‘task’] = request.json[‘task’] return jsonify(task) @app.route(‘/tasks/<int:id>’, methods=[‘DELETE’]) def delete_task(id): global tasks tasks = [task for task in tasks if task[‘id’] != id] return jsonify({“result”: “Task deleted”}) |
Code Explanation
The provided Python code snippet demonstrates setting up a basic RESTful API using the Flask framework. It defines four endpoints, each corresponding to CRUD (Create, Read, Update, Delete) operations for task management:
- GET /tasks: Fetches and returns a list of all tasks.
- POST /tasks: Adds a new task with an auto-incrementing ID.
- PUT /tasks/<int:id>: Updates the description of a task based on its unique ID.
- DELETE /tasks/<int:id>: Removes a task by its ID.
Common Mistakes to Watch Out For |
|
Follow-ups |
|
What the Question Tests | This question assesses the candidate’s understanding of RESTful API development using Python and Flask. It tests their ability to set up a simple server, define routes, handle HTTP methods, and perform CRUD operations. The task also evaluates the candidate’s skill in working with JSON data and managing state within a RESTful service. |
2. Implement Pagination in a REST API
Task | Modify the Python Flask API used for managing tasks to support pagination. The API should return a subset of tasks based on the provided limit and offset query parameters. |
Input Format | For fetching tasks, the API URL might be structured as /tasks?offset=2&limit=3. |
Constraints |
|
Output Format | The output should be in JSON format, showing a subset of tasks as determined by the offset and limit parameters. |
Suggested Answer
@app.route(‘/tasks’, methods=[‘GET’])
def get_tasks(): offset = int(request.args.get(‘offset’, 0)) limit = int(request.args.get(‘limit’, len(tasks))) paginated_tasks = tasks[offset:offset + limit] return jsonify(paginated_tasks) |
Code Explanation
This revised get_tasks function implements pagination using the offset and limit query parameters. The function retrieves these parameters from the request’s query string, using default values if they are not provided. The tasks list is then sliced according to these parameters, allowing the function to return only the relevant subset of tasks.
This approach is a straightforward yet effective way to handle pagination in a REST API. It enables the API to handle large sets of data efficiently by returning only a portion of the data at a time based on the client’s request. This method is particularly useful for improving the performance and user experience in applications where large datasets are involved.
Common Mistakes to Watch Out For |
|
Follow-ups |
|
What the Question Tests | This question assesses the candidate’s understanding of implementing pagination in REST APIs, a common technique for managing large datasets. It evaluates their ability to modify existing API functionality to include additional features and their understanding of handling query parameters. The task also tests the candidate’s proficiency in slicing lists in Python and returning structured data in JSON format. |
3. Implement Basic Authentication
Task | Modify the previous Flask API for managing tasks to include basic authentication for all operations, except for retrieving the list of tasks (the GET method). |
Input Format | API requests should include basic authentication headers. |
Constraints | Assume a single user with a username of “admin” and a password of “password” for simplicity. |
Output Format | Unauthorized requests should return a 401 status code. Otherwise, the API behaves as in previous examples. |
Suggested Answer
from flask import Flask, jsonify, request, abort
from functools import wraps app = Flask(__name__) # … (previous code for task management) def check_auth(username, password): return username == ‘admin’ and password == ‘password’ def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): abort(401) return f(*args, **kwargs) return decorated @app.route(‘/tasks’, methods=[‘POST’, ‘PUT’, ‘DELETE’]) @requires_auth def manage_tasks(): # … (previous code for POST, PUT, DELETE methods) |
Code Explanation
The provided code snippet integrates basic authentication into the Flask API. The check_auth function validates the provided username and password. The requires_auth decorator function uses check_auth to verify authentication details in incoming requests. The server responds with a 401 Unauthorized status code if the credentials are incorrect or not provided.
The requires_auth decorator is applied to the routes that handle POST, PUT, and DELETE methods, ensuring that only authenticated requests can perform these operations. The GET method for retrieving tasks remains accessible without authentication.
Common Mistakes to Watch Out For |
|
Follow-ups |
|
What the Question Tests | This question assesses the candidate’s understanding of basic authentication in REST APIs using Flask. It tests their ability to implement security measures to protect API endpoints and ensure that only authorized users can perform certain operations. The task also evaluates the candidate’s knowledge of Python decorators and handling HTTP headers, which is crucial for developing secure web applications. |
4. Implement Rate Limiting
Task | Introduce rate limiting in the Flask API used for managing tasks. Set a limit of 10 requests per minute for each client on any type of operation. |
Input Format | Standard API requests, as in previous examples. |
Constraints | The rate limit should be applied per the client’s IP address. |
Output Format | Clients exceeding the rate limit should receive a 429 status code with the message “Too many requests.” |
Suggested Answer
from flask import Flask, jsonify, request, abort, make_response
from time import time from functools import wraps app = Flask(__name__) client_times = {} def rate_limit(f): @wraps(f) def decorated(*args, **kwargs): client_ip = request.remote_addr current_time = int(time()) requests = client_times.get(client_ip, []) # Filter requests in the last minute requests = [req_time for req_time in requests if current_time – req_time < 60] if len(requests) >= 10: return make_response(jsonify({“error”: “Too many requests”}), 429)
requests.append(current_time) client_times[client_ip] = requests
return f(*args, **kwargs)
return decorated @app.route(‘/tasks’, methods=[‘GET’, ‘POST’, ‘PUT’, ‘DELETE’]) @rate_limit def manage_tasks(): # … (previous code for GET, POST, PUT, DELETE methods) |
Code Explanation
The rate_limit decorator function is implemented to control the number of requests a client can make within a minute. This function maintains a record of request timestamps in the client_times dictionary, indexed by the client’s IP address.
For each request, the function calculates the number of requests made by the client in the last 60 seconds. If the count exceeds 10, the server responds with a 429 status code, indicating too many requests. The rate limiting is applied to all HTTP methods (GET, POST, PUT, DELETE) by attaching the rate_limit decorator to the manage_tasks function, which handles these requests.
Common Mistakes to Watch Out For |
|
Follow-ups |
|
What the Question Tests | This question assesses the candidate’s understanding of implementing rate limiting in REST APIs. It tests their ability to use Python decorators, manage state across multiple requests, and handle client IP addresses. The task also evaluates their proficiency in writing middleware-like functions in Flask and enhancing API security and stability by controlling the load on the server. |
5. Implement API Versioning
Task | Extend the Flask API for task management to support two versions, v1 and v2. In v2, the task object should include an additional field called status. |
Input Format | The API version should be specified in the URL, such as /v1/tasks for version 1 and /v2/tasks for version 2. |
Constraints | In version v2, the status field is a string and can have values like “pending,” “completed,” or “archived.” |
Output Format | For v1, the task object remains unchanged from previous examples. For v2, the task object should include the status field. |
Suggested Answer
from flask import Flask, jsonify, request
app = Flask(__name__) tasks_v1 = [] tasks_v2 = [] task_id = 1 @app.route(‘/v1/tasks’, methods=[‘GET’, ‘POST’]) def manage_tasks_v1(): global task_id # … (previous code for v1) return jsonify(tasks_v1) @app.route(‘/v2/tasks’, methods=[‘GET’, ‘POST’]) def manage_tasks_v2(): global task_id if request.method == ‘POST’: new_task = {“id”: task_id, “task”: request.json[‘task’], “status”: “pending”} tasks_v2.append(new_task) task_id += 1 return jsonify(new_task) return jsonify(tasks_v2) |
Code Explanation
The provided code introduces API versioning by creating separate routes for v1 and v2 of the task management API. The v1 route (/v1/tasks) functions as before, handling tasks without the status field.
The v2 route (/v2/tasks), however, manages tasks with the additional status field.
- For v1, tasks are managed using the original task structure.
- For v2, each new task is created with a status field, initially set to “pending.”
This approach to versioning allows the API to evolve while maintaining backward compatibility for existing clients that use the v1 endpoint. It exemplifies how to manage different API versions within the same application, catering to varying client requirements.
Common Mistakes to Watch Out For |
|
Follow-ups |
|
What the Question Tests | This question assesses the candidate’s understanding of API versioning and its implementation in a RESTful service using Flask. It tests their ability to extend an existing API to support multiple versions, ensuring backward compatibility while introducing new features. The task also evaluates the candidate’s foresight in planning for API evolution and maintaining a consistent experience for different API consumers. |
6. Custom HTTP Status Codes and Error Handling
Task | Update the Flask API to return custom error messages along with appropriate HTTP status codes for different error scenarios. |
Input Format | Standard API requests, as in previous examples. |
Constraints |
|
Output Format | The API should return JSON-formatted error messages along with appropriate HTTP status codes. |
Suggested Answer
from flask import Flask, jsonify, request, make_response
app = Flask(__name__) tasks = [] @app.route(‘/tasks/<int:task_id>’, methods=[‘GET’, ‘PUT’, ‘DELETE’]) def manage_single_task(task_id): task = next((item for item in tasks if item[‘id’] == task_id), None) if task is None: return make_response(jsonify({“error”: “Task not found”}), 404) if request.method == ‘PUT’: if ‘task’ not in request.json: return make_response(jsonify({“error”: “Missing fields in request”}), 400) task[‘task’] = request.json[‘task’] return jsonify(task) # … (previous code for GET and DELETE methods) |
Code Explanation
In this modified manage_single_task function, error handling is implemented for two scenarios:
- Task Not Found (404 Not Found): If a client requests a task that does not exist (based on the task_id), the API responds with a 404 status code and a custom error message “Task not found.”
- Missing Fields in Request (400 Bad Request): When a PUT request is made to update a task but lacks the required task field in the JSON payload, the API responds with a 400 status code and a custom error message “Missing fields in request.”
This approach ensures that the API provides more informative and user-friendly error responses, making it easier for clients to understand and resolve issues when interacting with the API.
Common Mistakes to Watch Out For |
|
Follow-ups |
|
What the Question Tests | This question tests the candidate’s understanding of proper error handling in REST APIs and the use of HTTP status codes. It evaluates their ability to implement custom error responses that enhance the usability and debuggability of the API. The task also assesses the candidate’s knowledge of Flask routing and request handling, along with their proficiency in creating more user-friendly and robust web services. |
Conclusion
In the complex and ever-evolving world of software development, the ability to conduct insightful and effective technical interviews is crucial, especially when assessing candidates for roles involving REST APIs. The selection of the right interview questions is not just about testing knowledge; it’s about gauging a candidate’s ability to apply that knowledge in real-world scenarios.
The top 6 REST API interview questions discussed in this guide are designed to challenge candidates and probe their understanding of REST API concepts, from basic functionalities to more advanced topics like authentication, versioning, and error handling.
For hiring managers, structuring and conducting these technical interviews can be daunting. However, Interview Zen offers a solution that significantly simplifies and enhances this process. By leveraging this platform, hiring managers can create a more organized and efficient interview environment that allows for a comprehensive assessment of a candidate’s REST API skills.
We invite hiring managers and technical recruiters to consider using Interview Zen for their next REST API technical interview. With our user-friendly interface and a wide array of tools, Interview Zen streamlines the process of conducting technical interviews, ensuring a more effective assessment of candidates.
To begin using Interview Zen and transform your approach to REST API interviews, visit Interview Zen today.
Don’t miss the opportunity to elevate your hiring practice to the next level. Try Interview Zen for your next round of technical interviews.
Read more articles: