0
0
Rest APIprogramming~20 mins

Statelessness requirement in Rest API - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
REST API Statelessness Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this REST API statelessness simulation?

Consider a simple REST API simulation where each request is independent. The server does not store any client session data. What will be the output of the following code simulating two requests?

Rest API
class Server:
    def __init__(self):
        self.data = {}

    def handle_request(self, request):
        # Each request includes all needed info
        if request.get('action') == 'store':
            key = request.get('key')
            value = request.get('value')
            # Store data only for this request
            return f"Stored {key}={value}"
        elif request.get('action') == 'retrieve':
            key = request.get('key')
            # No stored data from previous requests
            return f"Value for {key}: None"

server = Server()

# First request stores data
print(server.handle_request({'action': 'store', 'key': 'x', 'value': '10'}))
# Second request tries to retrieve data
print(server.handle_request({'action': 'retrieve', 'key': 'x'}))
AStored x=10\nValue for x: 10
BStored x=10\nValue for x: None
CValue for x: None\nStored x=10
DValue for x: 10\nStored x=10
Attempts:
2 left
💡 Hint

Remember that stateless means the server does not keep data between requests.

🧠 Conceptual
intermediate
1:30remaining
Which statement best describes statelessness in REST APIs?

Choose the statement that correctly explains the statelessness requirement in REST APIs.

AEach request from client to server must contain all information needed to understand and process the request.
BThe server must store session data to track client state between requests.
CClients should never send authentication information with requests.
DThe server maintains a continuous connection to remember client data.
Attempts:
2 left
💡 Hint

Think about how REST APIs handle client data across multiple requests.

🔧 Debug
advanced
2:30remaining
Why does this REST API server violate statelessness?

Examine the code below. Why does this server violate the statelessness requirement?

Rest API
class Server:
    def __init__(self):
        self.sessions = {}

    def handle_request(self, request):
        session_id = request.get('session_id')
        if session_id not in self.sessions:
            self.sessions[session_id] = {'count': 0}
        self.sessions[session_id]['count'] += 1
        return f"Request count: {self.sessions[session_id]['count']}"
AThe server stores session data in self.sessions, keeping client state between requests.
BThe server does not handle requests properly because it lacks a session_id.
CThe server returns the wrong count value due to a syntax error.
DThe server is stateless because it uses session_id in requests.
Attempts:
2 left
💡 Hint

Check if the server keeps any data between requests.

Predict Output
advanced
1:30remaining
What error does this stateless REST API code produce?

What error will this code produce when handling a request missing required data?

Rest API
def handle_request(request):
    # Expect 'user_id' in request
    user_id = request['user_id']
    return f"User ID is {user_id}"

print(handle_request({'action': 'get_data'}))
ANo error, prints 'User ID is None'
BValueError: invalid user_id
CKeyError: 'user_id'
DTypeError: missing 1 required positional argument
Attempts:
2 left
💡 Hint

What happens if you try to access a dictionary key that does not exist?

🚀 Application
expert
3:00remaining
How many items are stored in the server after these stateless requests?

A REST API server is designed to be stateless. It receives three requests in order:

  1. {"action": "add", "item": "apple"}
  2. {"action": "add", "item": "banana"}
  3. {"action": "list"}

The server code is:

class Server:
    def __init__(self):
        pass

    def handle_request(self, request):
        if request['action'] == 'add':
            # Does not store items
            return f"Added {request['item']}"
        elif request['action'] == 'list':
            # Always returns empty list
            return []

server = Server()
print(server.handle_request({"action": "add", "item": "apple"}))
print(server.handle_request({"action": "add", "item": "banana"}))
print(server.handle_request({"action": "list"}))

How many items will the server list after these requests?

ACannot determine
B1
C2
D0
Attempts:
2 left
💡 Hint

Think about whether the server keeps any data between requests.