Skip to main content

How to support both JSON or Form Data in Flask Routes ?

I have been recently working on a flask web API project. One of my API routes' is expecting data to be posted from a form, or sent via JSON payload (Swagger UI).  In this blog, we'll explore a smart approach to handling both JSON and form data seamlessly within your Flask routes. The challenge was in creating routes that can gracefully handle both scenarios without cumbersome if-else blocks.

data = request.json or request.form.to_dict()

This single line of code drastically simplifies the route's logic. Let's break it down:

  • request.json attempts to parse the incoming data as JSON. If the data isn't in JSON format, it returns None.
  • request.form.to_dict() takes care of parsing form data into a dictionary. This method returns an empty dictionary if no form data is present.

By using the or operator, we create a neat and efficient way to handle both JSON and form payload scenarios. 

from flask import Flask, request

app = Flask(__name__)

@app.route('/process_data', methods=['POST'])
def process_data():
    data = request.json or request.form.to_dict()
     
    # Now you can work with the 'data' dictionary that contains the parsed payload
    username = data["username"]  
    return f'Data processed successfully for {username}'

if __name__ == '__main__':
    app.run()





Comments

Popular posts from this blog

Happy Anniversary

Dec 2010, 6.15 PM, Thoraipakkam, Chennai Gavin alights from the shared auto, thinking to himself, "for gods sake its my first date ever and can I for once afford to have a non-creased t shirt travelling in this over cramped vehicle, great choice."   His mind shifts to the attire selection, "well this is my best , I wore this in Helsinki , Blue Levi Jeans , Black Puma T-Shirt albeit all purchased on discount from t-nagar sarvana stores. Are these fake ? I don’t want to know the answer," he thinks to himself. He looks down on his most dear possession his black fossil watch, time is 6.25. We have been meeting regularly in office, however this is the moment of truth. "Time to call Rachel buddy," he says to himself. As he reaches to his phone and the thought of calling Rachel races through his mind, his heart starts pounding at a speed he had felt only once - as a 6th grade student in military school when he had to jump and climb the 10 feet wall of the insu...

Telecom Churn Case Study Upgrad - Kaggle Competition - Godwin Paul Notebook

Telecom Churn Case Study Upgrad Telecom Churn Case Study ¶ Overview ¶ In the telecom industry, customers are able to choose from multiple service providers and actively switch from one operator to another. In this highly competitive market, the telecommunications industry experiences an average of 15-25% annual churn rate. Given the fact that it costs 5-10 times more to acquire a new customer than to retain an existing one, customer retention has now become even more important than customer acquisition. For many incumbent operators, retaining high profitable customers is the number one business goal. Business Objective ¶ The objective is to reduce customer churn and improve customer retention in a highly competitive market. Retaining high profitable customers is the number one business goal Case Study Objective ¶ The goal is to build a machine learning model using customer-level data to identify customers at high...

Llamhub SnowflakeReader: A Loader to query and chat Snowflake Data in your LLM Applications

  Snowflake Loader for LLM Recently my second contribution to Llamaindex "SnowflakeReader" was merged to Lllamahub repository. This loader connects to Snowflake (using SQLAlchemy under the hood). The user specifies a query and extracts Document objects corresponding to the results. This loader is designed to be used as a way to load data into  LlamaIndex  and/or subsequently used as a Tool in a  LangChain  Agent.  Usage Option 1: Pass your own SQLAlchemy Engine object of the database connection Here's an example usage of the SnowflakeReader. from llama_index import download_loader SnowflakeReader = download_loader ( 'SnowflakeReader' ) reader = SnowflakeReader ( engine = your_sqlalchemy_engine , ) query = "SELECT * FROM your_table" documents = reader . load_data ( query = query ) Option 2: Pass the required parameters to esstablish Snowflake connection Here's an example usage of the SnowflakeReader. from llama_index import down...