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