杰瑞科技汇

Python JSON Server 如何快速搭建?

Of course! When someone asks about a "Python JSON server," they usually mean one of two things:

Python JSON Server 如何快速搭建?-图1
(图片来源网络,侵删)
  1. A simple, temporary server for testing API endpoints that return JSON data. This is the most common use case for developers.
  2. A full-fledged web framework (like Flask or Django) that is used to build a production-ready API that serves JSON.

I'll cover both, starting with the simplest and most direct answer.


Option 1: The Quick & Easy Way (Using Python's Built-in http.server)

This is perfect for quick tests, local development, or when you don't want to install any external libraries. It creates a basic HTTP server that can serve files from a directory, including JSON files.

Step 1: Create a JSON File

First, create a file named data.json in a new directory. This will be the "database" our server will serve.

data.json

Python JSON Server 如何快速搭建?-图2
(图片来源网络,侵删)
{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "email": "alice@example.com"
    },
    {
      "id": 2,
      "name": "Bob",
      "email": "bob@example.com"
    }
  ]
}

Step 2: Create a Simple Python Server

In the same directory, create a Python script named server.py. This script will use Python's built-in modules to create a server that knows how to handle JSON files with the correct Content-Type header.

server.py

import http.server
import socketserver
import json
# Define the port number
PORT = 8000
# Create a custom handler to set the correct Content-Type for JSON files
class JSONHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # If the request is for a JSON file, set the correct content type
        if self.path.endswith('.json'):
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            # Read the JSON file and send its content
            with open(self.path[1:], 'rb') as f: # [1:] to remove the leading '/'
                self.wfile.write(f.read())
        else:
            # For other files, use the default handler
            super().do_GET()
# Create the server
with socketserver.TCPServer(("", PORT), JSONHandler) as httpd:
    print(f"Serving at port {PORT}")
    print(f"Open your browser and go to: http://localhost:{PORT}/data.json")
    # Start serving
    httpd.serve_forever()

Step 3: Run the Server

Open your terminal or command prompt, navigate to the directory you created, and run the script:

python server.py

You should see the output:

Python JSON Server 如何快速搭建?-图3
(图片来源网络,侵删)
Serving at port 8000
Open your browser and go to: http://localhost:8000/data.json

Step 4: Test the Server

Now you can test it!

  • In your browser: Navigate to http://localhost:8000/data.json. You will see the raw JSON content.

  • Using curl (from another terminal):

    curl http://localhost:8000/data.json
  • Using Python (to make a request):

    import requests
    response = requests.get('http://localhost:8000/data.json')
    print(response.status_code)  # Should be 200
    print(response.json())       # Parses the JSON response into a Python dict

Option 2: The "Real" API Way (Using Flask)

For anything more than a simple file server, you'll want a web framework. Flask is a lightweight and excellent choice for building APIs. It gives you full control over the logic and the JSON response.

Step 1: Install Flask

If you don't have it installed, open your terminal and run:

pip install Flask

Step 2: Create the Flask API Script

Create a file named app.py.

app.py

from flask import Flask, jsonify, request
# Create a Flask application instance
app = Flask(__name__)
# This is our "database" - a simple Python list of dictionaries
# In a real app, this would come from a database or other sources
users_db = [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"}
]
# Define a route for the root URL that returns a welcome message
@app.route('/')
def index():
    return jsonify({"message": "Welcome to the JSON API!"})
# Define a route to get all users
@app.route('/users', methods=['GET'])
def get_users():
    return jsonify({"users": users_db})
# Define a route to get a single user by ID
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    # Find the user in our database
    user = next((user for user in users_db if user['id'] == user_id), None)
    if user:
        return jsonify(user)
    else:
        # Return a 404 Not Found error if the user doesn't exist
        return jsonify({"error": "User not found"}), 404
# Define a route to create a new user
@app.route('/users', methods=['POST'])
def create_user():
    if not request.json or 'name' not in request.json or 'email' not in request.json:
        return jsonify({"error": "Bad request: 'name' and 'email' are required"}), 400
    new_user = {
        'id': users_db[-1]['id'] + 1, # Simple ID generation
        'name': request.json['name'],
        'email': request.json['email']
    }
    users_db.append(new_user)
    return jsonify(new_user), 201 # 201 Created
# This allows the script to be run directly
if __name__ == '__main__':
    # Use debug=True for development to auto-reload on changes
    app.run(debug=True)

Step 3: Run the Flask Server

In your terminal, run the script:

python app.py

You'll see output like this, indicating the server is running:

 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: ...

Step 4: Test the API Endpoints

Flask's default port is 5000. You can test these endpoints using curl or a tool like Postman.

  • Get all users:

    curl http://127.0.0.1:5000/users

    Response:

    {
      "users": [
        {"id": 1, "name": "Alice", "email": "alice@example.com"},
        {"id": 2, "name": "Bob", "email": "bob@example.com"}
      ]
    }
  • Get a single user (ID 1):

    curl http://127.0.0.1:5000/users/1

    Response:

    {
      "email": "alice@example.com",
      "id": 1,
      "name": "Alice"
    }
  • Create a new user:

    curl -X POST -H "Content-Type: application/json" -d '{"name": "Charlie", "email": "charlie@example.com"}' http://127.0.0.1:5000/users

    Response (201 Created):

    {
      "email": "charlie@example.com",
      "id": 3,
      "name": "Charlie"
    }

Summary: Which one should you use?

Feature Python's http.server Flask (or Django/FastAPI)
Simplicity Excellent. No installation needed. Good. Requires pip install flask.
Setup Very minimal. A bit more boilerplate code.
Flexibility Low. It's a static file server. You can't add logic. Excellent. Full control over responses, logic, and data sources.
Use Case - Quickly sharing a JSON file.
- Testing a frontend app against a static mock API.
- Building a real, dynamic API.
- Connecting to a database.
- Handling user authentication, requests, and business logic.
Production Not recommended. Not secure or performant. Recommended. Designed for building real applications.
分享:
扫描分享到社交APP
上一篇
下一篇