Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Forwarding a Shortened URL

00:00 Forward a Shortened URL. Your Python URL shortener app aims to provide shortened URLs that forward to a target URL. This means your app needs to have a route that forwards to the target URL.

00:16 In more technical terms, the forwarding behavior means that you need to redirect HTTP requests with URL.key to the URL.target_url address.

00:30 Update to implement a RedirectResponse. For the redirecting behavior your app needs, you need to use the Request and RedirectResponse classes, so these are added to the imports. RedirectResponse returns an HTTP redirect that forwards the request of the client.

00:50 Next you add the raise_not_found() function. Similar to the raise_bad_request() function that was added earlier on, you’ll use raise_not_found() if the provided URL.key doesn’t match any URLs in your database.

01:06 Unlike raise_bad_request(), where you passed in a message, raise_not_found() always returns the same message. Canonically, you send back the 404 HTTP status code in the HTTPException.

01:26 Next you create the forward_to_target_url() function with an @app.get decorator. When you use the @app.get decorator, you allow GET requests for the URL that you provide as an argument. With the argument provided, the forward_to_target_url() function will be called any time a client requests the URL that matches the host and key pattern.

01:56 In these lines, you look for an active URL entry with the provided url_key in your database.

02:10 If a database entry is found, then you return the RedirectResponse with target_url. If no matching database entry is found, then you raise the HTTPException. In your browser, try out the behavior you just implemented.

02:29 First, go to the documentation at the /docs URL seen on-screen and create a POST request to your create_url endpoint.

02:52 Copy the key that you receive in response and try out the forwarding.

03:11 In the example seen on-screen, the URL forwards successfully to That’s almost perfect, but why only almost? Well, although the code works, both create_url() and forward_to_target_url() have shortcomings.

03:28 In the next section of the course, you’ll clean up your code before creating more functionality and endpoints for your Python URL shortener app.

Become a Member to join the conversation.