Open In App

Python Falcon – Request & Response

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python Falcon, a nimble web framework, simplifies the process of building web APIs by efficiently managing incoming requests, which are messages asking for something from your API, and providing an easy way to create structured responses that Falcon then sends back to the requester, making it a swift and scalable choice for API development in Python.

Python Falcon – Request & Response

In Falcon, handling requests is achieved through resource classes. These classes, responsible for specific routes, define methods for various HTTP methods like GET, POST, etc. Let’s discuss a basic example:

Example 1:

In this example, the on_get method retrieves the name query parameter from the request, defaulting to Guest if absent. The below code sets up a Falcon web API with a single resource, `HelloNameResource`, responding to GET requests at ‘/hello’. It retrieves a ‘name’ parameter from the request, defaulting to ‘Guest’ if absent, and returns a personalized greeting. The server runs on http://127.0.0.1:8000, allowing users to access personalized greetings by appending a name to ‘/hello’.

Python3




import falcon
 
class HelloNameResource:
    def on_get(self, req, resp):
        # Retrieve the 'name' parameter from the request, defaulting to 'Guest' if not present
        name = req.params.get("name", "Guest")
 
        # Build the response body with a personalized greeting
        resp.text = f"Hello, {name}!"
 
# Create a Falcon API instance
api = falcon.App()
 
# Add the HelloNameResource to the API, associating it with the endpoint '/hello'
api.add_route("/hello", HelloNameResource())
 
if __name__ == "__main__":
    from wsgiref import simple_server
 
    # Set the host and port for the Falcon application
    host = "127.0.0.1"
    port = 8000
 
    # Create a simple WSGI server using wsgiref and serve the Falcon application
    httpd = simple_server.make_server(host, port, api)
    print(f"Serving on http://{host}:{port}")
 
    # Serve requests indefinitely
    httpd.serve_forever()


Run the Server

python script_name.py

Output

second-In Falcon `Response` is an object representing the HTTP response, allowing customization of status codes, headers, and body content in a Falcon API endpoint. It is used to define what the API should return to the client.

Example 2:

In this example, When a GET request is sent to the ‘/course-cart‘ endpoint, it returns an HTML response with information about GeeksforGeeks courses such as name, level, interest, and rating. The HTML response is an HTML document that includes a title, header, and list of courses. Falcon’s response object attributes are then set to define the HTTP status as 200 (OK), the response text as the generated HTML, the content type as ‘text/html’, and a ‘Cache-Control’ header to prevent caching. The Falcon application is created, and the ‘/course-cart’ endpoint is linked to the CourseCartResource class.

Python3




import falcon
 
# GeeksforGeeks Courses Data in JSON format
course_data = [
    {
        "name": "DSA to Development: A Complete Guide",
        "level": "Beginner to Advance",
        "interest": "125k+ interested Geeks",
        "rating": "5",
    },
    {
        "name": "Full Stack Development with React & Node JS - Live",
        "level": "Beginner to Advance",
        "interest": "195k+ interested Geeks",
        "rating": "4.7",
    },
]
 
 
# Define a Falcon resource class named CourseCartResource
class CourseCartResource:
    def on_get(self, req, resp):
        # Convert the list of courses to an HTML response
        html_data = (
            "<html>\n<head><title>GeeksforGeeks Course Cart</title></head>\n<body>\n"
        )
        html_data += "<h1>GeeksforGeeks Course Cart</h1>\n<ul>\n"
        for course in course_data:
            html_data += (
                f"<li><strong>{course['name']}</strong><br>"
                f"Level: {course['level']}<br>"
                f"Interest: {course['interest']}<br>"
                f"Rating: {course['rating']}</li>\n"
            )
        html_data += "</ul>\n</body>\n</html>"
 
        # Set response attributes for HTML format
        resp.status = falcon.HTTP_200
        resp.text = html_data
        resp.content_type = "text/html"
        resp.set_header("Cache-Control", "no-cache")
 
 
# Create a Falcon App instance
app = falcon.App()
 
# Add the CourseCartResource to the App, associating it with the '/course-cart' endpoint
app.add_route("/course-cart", CourseCartResource())
 
if __name__ == "__main__":
    from wsgiref import simple_server
 
    # Set the host and port for the Falcon application
    host = "127.0.0.1"
    port = 8000
 
    # Create a simple WSGI server using wsgiref and serve the Falcon application
    httpd = simple_server.make_server(host, port, app)
    print(f"Serving on http://{host}:{port}")
    # Serve requests indefinitely
    httpd.serve_forever()


Run the Server

python script_name.py

Output:

single

Handle Request & Response ( Feedback Form )

python.py: This Python code uses the Falcon framework to create a simple API for handling feedback submissions. It begins by importing the necessary modules, including Falcon for building the API and Falcon CORS for enabling Cross-Origin Resource Sharing (CORS). The Falcon API instance is created, and CORS middleware is added to allow all origins, headers, and methods. The code defines a FeedbackResource class with a single method, on_post, which handles POST requests to the “/feedback” endpoint. The method extracts JSON data from the request body, processes the feedback (in this case, printing it to the console), and constructs an HTML response indicating successful feedback submission.

Python3




import falcon
from falcon_cors import CORS
 
# Create a Falcon API instance
app = falcon.App()
 
# Enable CORS
cors = CORS(allow_all_origins=True, allow_all_headers=True, allow_all_methods=True)
app.add_middleware(cors.middleware)
 
 
class FeedbackResource:
    def on_post(self, req, resp):
        # Parse the JSON data from the request body
        feedback_data = req.media
 
        # Process the feedback (in a real application, you might save it to a database)
        print(f"Received feedback: {feedback_data}")
 
        # Construct HTML response
        html_response = """
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Feedback Response</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f4f4f4;
                    margin: 0;
                    padding: 0;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                    flex-direction: column;
                }
 
                h1 {
                    color: green;
                }
 
                #response {
                    font-size: 18px;
                    color: #333;
                    display: flex;
                    align-items: center;
                }
 
                .tick {
                    margin-right: 10px;
                    color: #4caf50;
                }
            </style>
        </head>
        <body>
            <h1>GeeksforGeeks</h1>
            <div id="response">
                <span class="tick">✔</span> Feedback received successfully
            </div>
        </body>
        </html>
        """
 
        # Set the HTML response
        resp.content_type = falcon.MEDIA_HTML
        resp.text = html_response
        resp.status = falcon.HTTP_200
 
 
# Add the FeedbackResource to the API
app.add_route("/feedback", FeedbackResource())
 
if __name__ == "__main__":
    from wsgiref import simple_server
 
    # Run the Falcon API
    httpd = simple_server.make_server("127.0.0.1", 8000, app)
    print("Serving on http://127.0.0.1:8000")
    httpd.serve_forever()


Creating GUI

index.html : This HTML code represents a simple feedback form webpage. The document includes standard metadata, such as the document type declaration, character set, and viewport settings. It links an external stylesheet (“styles.css”) for styling. The inline styles define the layout and appearance of the form, with a flex container setting for centering content and specific styling for various form elements. The form collects user feedback, including their name and a message. Upon submission, the form sends a POST request to the “http://127.0.0.1:8000/feedback” endpoint. The form includes a title (“GeeksforGeeks”) and is styled with a clean and responsive design, making use of a green color theme. The response section, with an ID of “response,” is styled to display a success tick icon and a response message.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Feedback Form</title>
    <link rel="stylesheet" href="./styles.css">
</head>
  <style>
     
    body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    flex-direction: column;
}
 
h1 {
    color: green;
}
 
form {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 100%;
    margin-bottom: 20px;
}
 
label {
    display: block;
    margin-bottom: 8px;
}
 
input,textarea {
    width: 100%;
    padding: 8px;
    margin-bottom: 16px;
    box-sizing: border-box;
}
 
button {
    background-color: #4caf50;
    color: #fff;
    padding: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
 
#response {
    font-size: 18px;
    color: #333;
    display: flex;
    align-items: center;
}
 
.tick {
        margin-right: 10px;
        color: #4caf50;
}
     
  </style>
 
<body>
    <h1>GeeksforGeeks</h1>
    <form id="feedbackForm" action="http://127.0.0.1:8000/feedback" method="post">
        <label for="name">Your Name:</label>
        <input type="text" id="name" name="name" required>
        <label for="message">Feedback Message:</label>
        <textarea id="message" name="message" rows="4" required></textarea>
        <button type="submit">Submit Feedback</button>
    </form>
</body>
</html>


Run the Server

python script_name.py

Output:

Conclusion

Understanding request handling and response crafting is fundamental in Falcon development. Falcon’s simplicity and the power of its request and response objects make it a compelling choice for building robust and efficient web APIs. As you progress with Falcon, you’ll discover additional features enhancing your ability to create powerful and scalable web applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads