REST APIs & Flask-RESTful: past questions

23 questions · 78.5 marks · 10 papers. Try each one before checking.

Solve them and check answers →Read the notes first

24 Mar 2024

Question 5 MCQ · 2 marks

Consider the below Flask code snippet:

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/api/courses')
def get_courses():
    courses = [{'id': 'CS1001', 'name' : 'CT'}, {'id' : 'CS1002', 'name': 'PDSA'}]
    return jsonify(courses)

If the application is running locally, what will be the status code and mimetype of the response for the URL, http://127.0.0.1:5000/api/courses?

  1. status=404 and mimetype='application/json'
  2. status=200 and mimetype='application/json'
  3. status=200 and mimetype='text/javascript'
  4. status=404 and mimetype='text/javascript'

Question 17 MSQ · 4.5 marks

Consider the following api resources created using flask_restful. Assume that the app is connected to the database and is running on one terminal. Select the correct option(s).

class TestApi(Resource):
    def get(self, admin):
        # retrieves admin data from database and returns it.
        return {
            "name": "mad1_admin",
            "role": "admin",
        }

    def post(self):
        # fetches user data from request body and stores in the database.
        return {
            "message": "user added successfully"
        }, 201

api.add_resource(TestApi, "/api/<string:admin>", "/<admin>", "/user_data", "/")

app.run()

  1. The base URL for the app is mapped with GET HTTP method.
  2. If we run the command: curl http://127.0.0.1:5000/api/user -X GET on a new terminal; it will return; { "name": "mad1_admin", "role": "admin" }
  3. The endpoint, /<admin> is mapped with GET HTTP method.
  4. If we run the command: curl http://127.0.0.1:5000/user-data -X POST on a new terminal; it will return; { "message": "user added successfully" }

04 Aug 2024

Question 8 MSQ · 3 marks

Consider the following code.

from flask import Flask
from flask_restful import Resource, Api

trains_list = [
    {"train_no": 12842, "source": "Madras", "destination": "Howrah"},
    {"train_no": 12727, "source": "VSKP", "destination": "HYD"},
    {"train_no": 12434, "source": "Delhi", "destination": "Madras"},
]

app = Flask(__name__)
api = Api(app)

class TrainsApi1(Resource):
    def get(self, tno):
        for train in trains_list:
            if train["train_no"] == tno:
                return train
        return None

class TrainsApi2(Resource):
    def get(self):
        return trains_list

api.add_resource(TrainsApi1, "/api/ver1/<int:tno>")
api.add_resource(TrainsApi2, "/api/ver2/")

if __name__ == "__main__":
    app.run(debug=True)

Assume that the above flask code is running locally on http://127.0.0.1:5000/ . Which of the below URL(s) requests renders train data without errors?

  1. http://127.0.0.1:5000/api/ver1/12727
  2. http://127.0.0.1:5000/api/12727
  3. http://127.0.0.1:5000/ver2/12727
  4. http://127.0.0.1:5000/api/ver2

01 Dec 2024

Question 4 MCQ · 4.5 marks

Consider the following python code.

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

salaries = {
    1: {"name": "Ravi", "basic": 14500},
    2: {"name": "David", "basic": 9500},
    3: {"name": "Tinu", "basic": 15009},
}

class Salaries(Resource):
    def do_something(self):
        global salaries
        for s in salaries.keys():
            salaries[s]["hra"] = salaries[s]["basic"] * 0.10

    def get(self):
        self.do_something()
        return salaries

api.add_resource(Salaries, "/api/salaries")
app.run(debug=True)

Consider that the above code is running locally on "http://127.0.0.1:5000". What will the output for the URL: "http://127.0.0.1:5000/api/salaries"?

  1. { "1": {"hra": 1450.0}, "2": {"hra": 950.0}, "3": {"hra": 1500.9} }
  2. { "1": { "name": "Ravi", "basic": 14500, "hra": 1450.0 }, "2": { "name": "David", "basic": 9500, "hra": 950.0 }, "3": { "name": "Tinu", "basic": 15009, "hra": 1500.9 } }
  3. { "1": { "name": "Ravi", "basic": 14500 }, "2": { "name": "David", "basic": 9500 }, "3": { "name": "Tinu", "basic": 15009 } }
  4. { "1": { "basic": 14500, "hra": 1450.0 }, "2": { "basic": 9500, "hra": 950.0 }, "3": { "basic": 15009, "hra": 1500.9 } }

Question 8 MSQ · 3 marks

Consider the following flask code.

from flask import Flask
import json
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    def __str__(self) -> str:
        result = {
            "brand": self.brand,
            "model": self.model,
        }
        return str(result)

class MyApi(Resource):
    def get(self, brand, model):
        c = Car(brand, model)
        return json.dumps(c, default=vars)

api.add_resource(MyApi, "/api/<string:brand>/<string:model>")
app.run(debug=True)

If the flask server is running locally on "http://127.0.0.1:5000/". Which of the following URLs will result in a Not Found error?

  1. http://127.0.0.1:5000/api/maruti/swift
  2. http://127.0.0.1:5000/api/brand=Hundai/model=Creta
  3. http://127.0.0.1:5000/api/brand=Ford, model=Fiesta
  4. http://127.0.0.1:5000/api/Honda&City
  5. http://127.0.0.1:5000/api/model=Accent/brand=Hundai

Question 13 COMP · 4.5 marks

What will be returned on the terminal 2 for the command: curl http://127.0.0.1:5000/delete/val1

  1. {"message": "Value deleted successfully", "value": "val1"}
  2. {"message": "Value updated successfully", "value": "val1"}
  3. {"val1": "value1"}
  4. None of these.

Question 14 COMP · 3 marks

What will be returned on the terminal 2 for the command: curl http://127.0.0.1:5000/delete/val1 -X PUT

  1. {"message": "Value deleted successfully", "value": "val1"}
  2. {"message": "Value updated successfully", "value": "val1"}
  3. {"val1": "value1"}
  4. None of these.

16 Mar 2025

Question 10 MCQ · 4.5 marks

Consider the following Flask Restful API code:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class my_resource1(Resource):
    def get(self):
        return {"output": "Default computed value: 0"}, 200

class my_resource2(Resource):
    def get(self, x, y):
        c = x**y
        return {f"output": "Computed x^y =" + str(c)}, 200

api.add_resource(my_resource1, "/")
api.add_resource(my_resource2, "/<int:x>/<int:y>")

if __name__ == "__main__":
    app.run(debug=True)

Assume that the above code is running on "http://127.0.0.1:5000".

request URL rendered output
1) http://127.0.0.1:5000/ i) {"output": "Computed x^y =36"}
2) http://127.0.0.1:5000/x=6/y=2 ii) {"output": "Default computed value: 0"}
3) http://127.0.0.1:5000/6/2 iii) Not Found
4) http://127.0.0.1:5000/6 iv) {"output": "Default computed value: 6"}
5) http://127.0.0.1:5000/2 v) {"output": "Default computed value: 2"}

Based on the above table, choose the correct matching?

  1. 1-ii, 2-i, 3-iii, 4-iv, 5-v
  2. 1-iii, 2-iii, 3-iii, 4-v, 5-iv
  3. 1-ii, 2-i, 3-i, 4-iv, 5-v
  4. 1-ii, 2-iii, 3-i, 4-iii, 5-iii

Question 16 MSQ · 4.5 marks

Consider the following Flask-RESTful API implementation:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

students = {
    1: {"name": "Arjun", "grade": "A"},
    2: {"name": "Kiran", "grade": "B+"},
    3: {"name": "Meera", "grade": "A"},
}

class Student(Resource):
    def get(self, student_id):
        if student_id in students:
            return students[student_id], 200
        return {"message": "Student not found"}, 404

    def put(self, student_id):
        data = request.json
        if student_id in students:
            students[student_id]["grade"] = data.get("grade", students[student_id]["grade"])
            return {"message": "Student record updated", "student": students[student_id]}, 200
        return {"message": "Student not found"}, 404

api.add_resource(Student, "/student/<int:student_id>")

if __name__ == "__main__":
    app.run(debug=True)

The API is running on http://127.0.0.1:5000/. Which of the following statements about this API's behavior is correct?

  1. Sending a GET request to http://127.0.0.1:5000/student/2 will return: { "name": "Kiran", "grade": "B" } HTTP Status Code: 200
  2. Sending a PUT request to http://127.0.0.1:5000/student/4 with the following JSON payload: { "grade": "A+" } will return: { "message": "Student record updated", "student": {"name": "Unknown", "grade": "A+"} } HTTP Status Code: 200
  3. Sending a GET request to http://127.0.0.1:5000/student/10 will return: { "message": "Student not found" } HTTP Status Code: 404
  4. Sending a PUT request to http://127.0.0.1:5000/student/1 with the following JSON payload: { "grade": "A+" } will return: { "message": "Student record updated", "student": {"name": "Arjun", "grade": "A+"} } HTTP Status Code: 200

03 Aug 2025

Question 12 MSQ · 3 marks

Which of the following statements is/are false about caching in REST APIs?

  1. Caching allows storing server responses in a proxy or frontend so that a clientneed not make requests to the server for the same resources repeatedly.
  2. Caching degrades the overall quality of service and increases load on theservers.
  3. Browsers treat all GET and POST requests cacheable by default.
  4. Caching optimizes the network by increasing the latency.

Question 14 MSQ · 4.5 marks

Consider the Flask Restful API code given below: File name: app.py

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class APICalculator(Resource):
    def post(self):
        d = request.json
        a = int(d["val1"])
        b = int(d["val2"])
        oper = d["operator"]
        if oper == "+":
            return {"Sum=": (a + b)}, 200
        elif oper == "-":
            return {"Difference=": (a - b)}, 200
        elif oper == "*":
            return {"Product=": (a * b)}, 200
        else:
            return {"Error": "Invalid option"}, 401

api.add_resource(APICalculator, "/")
app.run(debug=True)

Assume that the Flask server is running on http://127.0.0.1:5000. Which of the following is the correct curl command(s) that will return calculated values? Note: Assume data sent is valid for cmd, and powershell

  1. curl -X POST "http://127.0.0.1:5000" -H 'Content-Type: application/json' -d '{"val1":27,"val2": 3, "operator":"+"}'
  2. curl -X POST "http://127.0.0.1:5000" -H 'Content-Type: application/json' -d '{"val1":27,"val2": 3, "operator":"*"}'
  3. curl -X POST "http://127.0.0.1:5000" -H 'Content-Type: application/json' -d '{"val1":27,"val2": 3, "operator":"/"}'
  4. curl -X POST "http://127.0.0.1:5000" -d '{"val1":27,"val2": 3, "operator":"/"}'
  5. curl -X POST "http://127.0.0.1:5000" -H 'Content-Type: application/json' -d '{"val1":27,"val2": 3, "operator":"-"}'

14 Aug 2026

Question 10 MCQ · 2 marks

What does the following curl command do? curl -X PUT -d "status=active&role=admin" https://api/users/update

  1. Sends a PUT request to update data using form format.
  2. Sends a PUT request using JSON encoding.
  3. Sends a GET request to retrieve user information.
  4. Sends a DELETE request to remove user data.

Question 12 MCQ · 4 marks

Consider the following Flask RESTful API code. File name: app.py

from flask_restful import reqparse, Resource, Api
from flask import Flask

parser = reqparse.RequestParser()
parser.add_argument("n", type=int, required=True)
app = Flask(__name__)
api = Api(app)

class MyResponse(Resource):
    def post(self):
        args = parser.parse_args()
        return args

api.add_resource(MyResponse, "/")
app.run(debug=True)

Assume that the Flask app is running at http://127.0.0.1:5000. The client sends the below CURL request in the git bash terminal.

curl -X POST http://127.0.0.1:5000 -H "Content-Type: application/json" -d "{\"n\":3}"

What will be the response?

  1. {"n": 3}
  2. Runtime error
  3. 400 Bad Request
  4. {}

Question 14 MSQ · 4 marks

Consider the following Flask app code.

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class UserResource(Resource):
    def get(self):
        return {"status": "GET request"}, 200

    def post(self, user_id):
        return {"status": "POST request", "user_id": user_id}, 201

api.add_resource(UserResource, "/users", "/users/<int:user_id>")

if __name__ == "__main__":
    app.run(debug=True)

The above flask app is running on "http://127.0.0.1:5000". Which of the following commands will return a runtime error?

  1. curl http://127.0.0.1:5000/users/5001 -X GET
  2. curl http://127.0.0.1:5000/users/5001 -X POST
  3. curl http://127.0.0.1:5000/users -X POST
  4. curl http://127.0.0.1:5000/users -X GET

July 2022

Question 10 MCQ · 2 marks

Consider the statements given below. Statement 1: APIs usually contain SDKs, but SDKs do not contain APIs. Statement 2: The SDKs contains the group of tools that help developers to use a different product or services. Which of the following is correct in the context of statements given above?

  1. Both statement 1 and 2 are correct.
  2. Statement 1 is correct, 2 is incorrect.
  3. Both statement 1 and 2 are incorrect.
  4. Statement 1 is incorrect, 2 is correct.

Question 3 MCQ · 3 marks

A flask application is given below.

from flask import Flask, jsonify

app = Flask(__name__)

Gadgets = [
    {"tech":"Smartwatch, Digital camera"},
    {"mobile":"Headphones, Speakers"},
    {"Laptop":"Keyboard, Mouse"}
]

@app.route("/home", methods=["GET"])
def func1():
    return jsonify({"The list of gadgets": Gadgets})

@app.route("/")
def rest_lists():
    return {
        "Restaurant 1" : "Hotel Alpine",
        "Restaurant 2" : "Maurya Vihar",
        "Restaurant 3" : "Royal Garden"
    }

if __name__ == "__main__":
    app.run(debug=True)

If the above flask application is running locally on the URL ‘http://127.0.0.1:5000', which of the following statement is true about the above flask application?

  1. For the endpoint "/", The content type of the response is ‘application/json’
  2. For the endpoint ‘/home', the application returns: "The list of gadgets": { "tech":"Smartwatch, Digital camera", "mobile":"Headphones, Speakers", "Laptop":"Keyboard, Mouse" }
  3. None of the endpoints, i.e., '/' or ‘/home' can be considered as access URIs of an API.
  4. For the endpoint ‘/home', the application returns: "The list of gadgets": { "tech": "Smartwatch, Digital camera" }, { "mobile": "Headphones, Speakers" }, { "Laptop": "Keyboard, Mouse" }

Question 17 MCQ · 4.5 marks

Consider the following Python code snippet:

from flask import Flask
from flask_restful import Resource, Api, reqparse, fields, marshal_with

app = Flask('__main__')
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument("Id")
parser.add_argument("name")
parser.add_argument("email")

out_fields = {
    "Id": fields.Integer,
    "name": fields.String
}

class MyApi (Resource):
    def get(self):
        info = parser.parse_args()
        return {"Identity": info['Id'], "Name": info['name'], "E-mail": info['email']}

    @marshal_with(out_fields)
    def post(self):
        info = parser.parse_args()
        return info

api.add_resource (MyApi, '/myinfo')
app.run(debug = True)

If the application is running locally on the URL: "http://127.0.0.1:5000", What will be the output on the terminal for command:

curl -X POST -H "Content-Type: application/json" -d "{\"Id\":3, \"name\":\"user_1\", \"email\": \"user_1@gmail.com\"}" http://127.0.0.1:5000/myinfo

  1. { "Identity": "3", "Name": "user_1", "E-mail": "user_1@gmail.com" }
  2. { "Id": 3, "name": "user_1" }
  3. { "Id": "3", "name": "user_1" }
  4. { "name": "user_1", "email": "user_1@gmail.com" }

Aug 2023

Question 3 MCQ · 2 marks

Which of the following statements about OpenAPI Specification (OAS) is true?

  1. OAS is a programming language used for building APIs.
  2. OAS is a way to describe interfaces for building RESTful APIs.
  3. OAS is a tool used for testing the performance of APIs.
  4. OAS is a software library used for authenticating API requests.

Question 8 MCQ · 3 marks

Consider the following Python code snippet.

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class MyApi (Resource):
    def get(self):
        return {"greet": "Hello from GET Api!"}
    def put(self):
        return {"greet": "Hello from PUT Api!"}

api.add_resource (MyApi, '/api/get', '/api/put', '/api/post')
app.run()

If this application is running locally on http://127.0.0.1:5000, which of the following curl commands will throw an error?

  1. curl http://127.0.0.1:5000/api/get -X get
  1. curl http://127.0.0.1:5000/api/put -X put
  1. curl http://127.0.0.1:5000/api/post -X post
  1. curl http://127.0.0.1:5000/api/get -X put
  1. curl http://127.0.0.1:5000/api/put -X get
  1. curl http://127.0.0.1:5000/api/post -X get
  1. Only 3
  2. Only 3 and 4
  3. Only 5 and 6
  4. Only 3, 4, 5 and 6

Dec 2023

Question 8 MCQ · 2 marks

In the context of API documentation, what is typically provided to describe the available endpoints, request parameters and response formats?

  1. API documentation or API reference
  2. API key
  3. Software source code
  4. OAuth tokens

Question 13 COMP · 3 marks

Map the api resources in column A with the correct URLs given in column B.

Column A Column B
1\. GET a. http://127.0.0.1:5000/student
2\. PUT b. http://127.0.0.1:5000/api/Meera
3\. POST c. http://127.0.0.1:5000/app/STU103/Sociology
  1. $1 \rightarrow c, 2 \rightarrow a, 3 \rightarrow b$
  2. $1 \rightarrow a, 2 \rightarrow b, 3 \rightarrow c$
  3. $1 \rightarrow b, 2 \rightarrow a, 3 \rightarrow c$
  4. $1 \rightarrow b, 2 \rightarrow c, 3 \rightarrow a$

Question 14 COMP · 3 marks

If the app first receives the request, curl http://127.0.0.1:5000/app/STU105/Robotics -X PUT what will be the final output on the shell after writing the following lines of code one below the other in the Python shell?

>>> from app import *
>>> students = Student.query.filter_by(name = "Ramesh").all()
>>> for student in students:
        print(student.course)

  1. Physics Physics
  2. Robotics Robotics
  3. Physics Robotics
  4. Robotics Physics

06 Apr 2026

Question 14 MSQ · 5 marks

Consider the following Python Flask RESTful API code.

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

products = [
    {"id": 1, "name": "books", "price": 56},
    {"id": 2, "name": "pens", "price": 61},
    {"id": 3, "name": "bulbs", "price": 76},
]

class MyApiResource(Resource):
    ### Missing code ###

api.add_resource(MyApiResource, "/<int:id>")

if __name__ == "__main__":
    app.run(debug=True)

Assume that the Flask app is running at http://127.0.0.1:5000. Which of the following codes when placed at ###Missing code ### will work correctly to search a product by id?

  1. def post(self): for p in products: if p["id"] == id: return f"{p['id']}, {p['name']}, {p['price']}" return f"msg: {id} not found"
  2. def get(self,id): for p in products: if p["id"] == id: return f"{p['id']}, {p['name']}, {p['price']}" return f"msg: {id} not found"
  3. def get(self): for p in products: if p["id"] == id: return f"{p['id']}, {p['name']}, {p['price']}" return f"msg: {id} not found"
  4. def post(self, id): for p in products: if p["id"] == id: return f"{p['id']}, {p['name']}, {p['price']}" return f"msg: {id} not found"

Check your answers →

Weeks covering this topic

Other MAD 1 topics