Consider this FastAPI endpoint using a simple in-memory cache dictionary. What will be the response when calling /data twice?
from fastapi import FastAPI app = FastAPI() cache = {} @app.get('/data') async def get_data(): if 'value' in cache: return {'data': cache['value']} cache['value'] = 'cached result' return {'data': 'cached result'}
Think about how the cache dictionary stores and returns the value.
The cache dictionary stores the value after the first call. On the second call, it returns the cached value without error.
Depends for caching?FastAPI allows dependency injection for caching. Which code snippet correctly uses Depends to inject a cache dependency?
Remember that Depends takes a callable without calling it.
Option A correctly passes the function get_cache to Depends without calling it. Other options either call the function or misuse Depends.
Given this code snippet, why might the cache return outdated data?
from fastapi import FastAPI app = FastAPI() cache = {'data': 'old'} @app.get('/update') async def update_data(): cache['data'] = 'new' return {'status': 'updated'} @app.get('/data') async def get_data(): return {'data': cache['data']}
Think about when the cache value changes and when it is read.
The cache starts with 'old'. It only updates when /update is called. If /data is called before /update, it returns the old cached value, which may be stale.
You have an API endpoint that returns data updated every minute. Which caching strategy is best to reduce load but keep data fresh?
Think about balancing freshness and performance with automatic expiration.
Using a TTL cache with 60 seconds expiry keeps data fresh and reduces server load by caching responses for one minute.
Given this FastAPI app, what is the output of calling /get after calling /set/5 and then /set/10?
from fastapi import FastAPI app = FastAPI() cache = {} @app.get('/set/{value}') async def set_value(value: int): cache['num'] = value return {'status': 'set', 'value': value} @app.get('/get') async def get_value(): return {'num': cache.get('num', 0)}
Consider the order of calls and how the cache dictionary updates.
The cache key 'num' is first set to 5, then overwritten to 10. The /get endpoint returns the latest cached value 10.