You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何将Python DataFrame以JSON格式通过Postman发送至Flask服务器

Got it, let's break this down into clear, actionable steps with code examples for every part:

1. Build the Flask Server (Data Receiver)

First, we'll create a simple Flask endpoint that accepts POST requests with JSON data, processes it, and sends a confirmation response.

Create a file named app.py with this code:

from flask import Flask, request, jsonify
import pandas as pd

app = Flask(__name__)

@app.route('/receive-data', methods=['POST'])
def receive_data():
    # Parse incoming JSON data from the request
    json_data = request.get_json()
    
    if not json_data:
        return jsonify({"error": "No data provided in the request"}), 400
    
    # Convert JSON back to a DataFrame (optional, for server-side data manipulation)
    df = pd.DataFrame(json_data)
    
    # Example processing: print the DataFrame to server console
    print("Received DataFrame:")
    print(df)
    
    # Send a success response with metadata about the received data
    return jsonify({
        "status": "success",
        "message": "Data received successfully",
        "number_of_rows": len(df),
        "columns": list(df.columns),
        "sample_rows": df.head(2).to_dict('records')
    }), 200

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

Quick Notes:

  • request.get_json() handles parsing the JSON payload automatically.
  • Converting back to a DataFrame is optional but useful if you need to clean, analyze, or store the data server-side.
  • Debug mode is great for testing, but remember to disable it in production.
2. Prepare & Convert Your 2-Column DataFrame to JSON

Next, let's create a sample 2-column DataFrame and convert it to a JSON format optimized for API requests.

Create a script named generate_data.py (or run this in a Python shell/Jupyter notebook):

import pandas as pd

# Create a sample 2-column DataFrame
data = {
    "Product": ["Laptop", "Phone", "Tablet", "Headphones"],
    "Price": [999, 699, 299, 149]
}
df = pd.DataFrame(data)

# Convert DataFrame to JSON (using 'records' orient for a clean, API-friendly structure)
json_output = df.to_json(orient='records', indent=2)
print("Generated JSON to send:")
print(json_output)

Key Detail:

Using orient='records' gives us a JSON array of objects (each object represents a row from the DataFrame), which is the most widely accepted format for API payloads. The output will look like this:

[
  {
    "Product": "Laptop",
    "Price": 999
  },
  {
    "Product": "Phone",
    "Price": 699
  },
  {
    "Product": "Tablet",
    "Price": 299
  },
  {
    "Product": "Headphones",
    "Price": 149
  }
]
3. Send the Request via Postman

Now let's send the JSON data to our Flask server:

  1. Install Dependencies First:
    Run these commands in your terminal to set up required packages:

    pip install flask pandas
    
  2. Start the Flask Server:
    Launch app.py with:

    python app.py
    

    You'll see output like Running on http://127.0.0.1:5000/—that's our server's base URL.

  3. Configure Postman:

    • Open Postman, click New > Request, name it (e.g., "Send DataFrame JSON"), and save it to a collection.
    • Set the request method to POST.
    • Enter the full endpoint URL: http://127.0.0.1:5000/receive-data
    • Go to the Body tab, select raw, and set the format dropdown to JSON.
    • Paste the JSON output you generated from the DataFrame into the text area.
    • Click Send.
  4. Verify the Response:
    You'll get a JSON response like this:

    {
      "status": "success",
      "message": "Data received successfully",
      "number_of_rows": 4,
      "columns": ["Product", "Price"],
      "sample_rows": [
        {"Product": "Laptop", "Price": 999},
        {"Product": "Phone", "Price": 699}
      ]
    }
    

    Also, check your Flask server terminal—you'll see the received DataFrame printed there.


内容的提问来源于stack exchange,提问作者Mohan Ram

火山引擎 最新活动