0
0
Rest APIprogramming~30 mins

301 and 302 redirects in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling 301 and 302 Redirects in a REST API
📖 Scenario: You are building a simple REST API server that handles URL redirects. Some URLs should permanently redirect to a new location (301), while others should temporarily redirect (302).
🎯 Goal: Create a Python REST API using Flask that returns 301 or 302 redirects based on the requested URL.
📋 What You'll Learn
Create a dictionary called redirects with URLs as keys and tuples as values. Each tuple contains the target URL and the redirect type (301 or 302).
Create a variable called default_redirect that holds the default redirect URL and type.
Write a Flask route /redirect/<path> that checks if the path is in redirects and returns the correct redirect response.
If the path is not found, redirect to default_redirect URL with its redirect type.
Print the redirect status code and target URL in the response.
💡 Why This Matters
🌍 Real World
Web servers and APIs often need to redirect old URLs to new ones, either permanently (301) or temporarily (302). This helps users and search engines find the right pages.
💼 Career
Understanding how to implement redirects is important for backend developers, web developers, and DevOps engineers managing web traffic and SEO.
Progress0 / 4 steps
1
Create the redirects dictionary
Create a dictionary called redirects with these exact entries: 'old-home': ('/new-home', 301), 'temp-page': ('/temporary', 302), and 'old-contact': ('/contact-us', 301).
Rest API
Need a hint?

Use a Python dictionary with keys as strings and values as tuples containing the target URL and redirect code.

2
Add the default redirect variable
Create a variable called default_redirect and set it to the tuple ('/home', 302).
Rest API
Need a hint?

Set default_redirect to a tuple with the URL '/home' and redirect code 302.

3
Create the Flask route for redirects
Import Flask and create an app. Write a route @app.route('/redirect/<path>') with a function redirect_url(path) that checks if path is in redirects. If yes, get the target URL and code from redirects[path]. Otherwise, use default_redirect. Return a Flask redirect response with the target URL and status code.
Rest API
Need a hint?

Use Flask's redirect() function with the target URL and status code.

4
Print redirect details on each request
Inside the redirect_url(path) function, before returning, add a print statement that outputs exactly: Redirecting to {target} with status {code} using an f-string.
Rest API
Need a hint?

Use an f-string inside print() to show the target and code.