Browse Courses

Dynamic Routes

This document explains how to use dynamic routes in Flask, including passing parameters in URLs, calling external APIs, and validating parameter types for RESTful endpoints.

This document explores dynamic routing in Flask, including how to pass parameters in URLs, call external APIs, and use parameter types for robust RESTful endpoints. It covers practical examples for integrating external data and validating user input in web applications.


Calling External APIs in Flask

Flask can interact with external APIs using the Python requests library. This allows applications to fetch, process, and return data from third-party services.

 1import requests
 2from flask import Flask, jsonify
 3
 4app = Flask(__name__)
 5
 6@app.route('/author')
 7def author_info():
 8    res = requests.get('https://openlibrary.org/search/authors.json?q=Michael+Crichton')
 9    if res.status_code == 200:
10        return jsonify(res.json())
11    elif res.status_code == 404:
12        return {'message': 'Something went wrong.'}, 404
13    else:
14        return {'message': 'Server error.'}, 500

This example fetches author data from the OpenLibrary API and returns the result to the client, handling different status codes appropriately.


Using Dynamic Routes and URL Parameters

Dynamic routes allow Flask endpoints to accept variable parts in the URL, enabling RESTful design and flexible data access.

1@app.route('/book/<string:isbn>')
2def book_info(isbn):
3    res = requests.get(f'https://openlibrary.org/isbn/{isbn}.json')
4    if res.status_code == 200:
5        return jsonify(res.json())
6    else:
7        return {'message': 'Book not found.'}, 404

In this example, the isbn parameter is passed dynamically in the URL, allowing clients to request information for any book by its ISBN.


Parameter Types in Flask Routes

Flask supports several parameter types for route variables, which help validate and convert incoming data:

TypeDescription
string(default) Accepts any text
intAccepts integers only
floatAccepts floating-point numbers
pathAccepts a path, including slashes
uuidAccepts a UUID (universally unique id)

Example: Using UUID in a Route

1from uuid import UUID
2
3@app.route('/network/<uuid:network_id>')
4def network_info(network_id):
5    # network_id is a UUID object
6    # Perform lookup or validation
7    return {'message': f'Network {network_id} found.'}

This route expects a UUID in the URL and passes it as a UUID object to the function.


Conclusion

Dynamic routes in Flask enable flexible, RESTful API design by allowing parameters in URLs and supporting type validation. Integrating external APIs and handling different parameter types makes Flask applications robust and adaptable to various data sources and user needs.


FAQ

  1. To serve only static files
  2. To allow variable parts in the URL for flexible endpoints
  3. To restrict access to certain users
  4. To handle only GET requests
(2) Dynamic routes allow variable parts in the URL, enabling flexible and RESTful endpoints.

Flask will return a 404 error because the parameter type does not match the route’s expectation.

The requests library is commonly used to call external APIs in Flask applications.

TypeDescription
A. string1. Accepts floating-point numbers
B. int2. Accepts any text
C. float3. Accepts integers only
D. uuid4. Accepts a universally unique id
A-2, B-3, C-1, D-4.

  1. You can return JSON data directly to the client
  2. You must always return a 200 status code
  3. You can return custom error messages with different status codes
  4. You can process API results before sending them to the client
(2) You do not have to always return a 200 status code; custom codes are allowed.

Flask allows the use of complex parameter types like UUID and path in dynamic routes.

True. Flask supports several parameter types, including string, int, float, path, and uuid.

The status code of the response should be checked first to determine if the request was successful.

They enable RESTful API design by allowing parameters in URLs and supporting type validation for robust endpoints.

The path parameter type allows the route to accept a value that can include slashes, such as a file or folder path.

The Flask application should return a 404 status code with a message indicating the book was not found.