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.
In more technical terms, the forwarding behavior means that you need to redirect HTTP requests with
URL.key to the
main.py to implement a
RedirectResponse. For the redirecting behavior your app needs, you need to use the
RedirectResponse classes, so these are added to the imports.
RedirectResponse returns an HTTP redirect that forwards the request of the client.
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.
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
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.
In these lines, you look for an active URL entry with the provided
url_key in your database.
If a database entry is found, then you return the
target_url. If no matching database entry is found, then you raise the
HTTPException. In your browser, try out the behavior you just implemented.
First, go to the documentation at the
/docs URL seen on-screen and create a POST request to your
key that you receive in response and try out the forwarding.
In the example seen on-screen, the URL forwards successfully to realpython.com. That’s almost perfect, but why only almost? Well, although the code works, both
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.