0
0
Rest APIprogramming~30 mins

Sliding window algorithm in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Sliding Window Algorithm with REST API
📖 Scenario: You are building a simple REST API that processes a list of numbers sent by users. The API will find the maximum sum of any continuous sub-list of a fixed size using the sliding window algorithm. This technique helps efficiently analyze data streams or time series.
🎯 Goal: Create a REST API endpoint that accepts a list of integers and a window size, then returns the maximum sum of any continuous sub-list of that size using the sliding window algorithm.
📋 What You'll Learn
Use Python with FastAPI to create the REST API
Accept JSON input with a list of integers called numbers and an integer window_size
Implement the sliding window algorithm to find the maximum sum of any continuous sub-list of length window_size
Return the maximum sum as JSON response
💡 Why This Matters
🌍 Real World
Sliding window algorithms are used in real-time data processing, such as analyzing sensor data, financial time series, or network traffic to find patterns or anomalies efficiently.
💼 Career
Understanding how to implement efficient algorithms and expose them via REST APIs is valuable for backend developers, data engineers, and software engineers working with data streams or microservices.
Progress0 / 4 steps
1
Set up the FastAPI app and input data model
Write code to import FastAPI and Pydantic's BaseModel. Create a FastAPI app called app. Define a Pydantic model called NumbersInput with two fields: numbers as a list of integers and window_size as an integer.
Rest API
Need a hint?

Remember to import FastAPI and BaseModel first. Then create the app and the input data model with the exact field names.

2
Create the API endpoint and receive input
Add a POST endpoint /max_sum_window to the app that accepts a JSON body of type NumbersInput. Inside the function, assign the input list to numbers and the window size to k.
Rest API
Need a hint?

Define the POST route and extract the input values into variables named exactly numbers and k.

3
Implement the sliding window algorithm to find max sum
Inside the max_sum_window function, write code to calculate the maximum sum of any continuous sub-list of length k using the sliding window algorithm. Use variables window_sum for the current window sum and max_sum for the maximum sum found. Iterate over the list with a for loop using i as the index.
Rest API
Need a hint?

Start by summing the first k numbers. Then slide the window by adding the new number and subtracting the old one. Update max_sum if the current window sum is bigger.

4
Return the maximum sum as JSON response
At the end of the max_sum_window function, return a dictionary with the key max_sum and the value as the calculated maximum sum.
Rest API
Need a hint?

Return a dictionary with the key max_sum and the value as the maximum sum found.