- Python 使用 Flask
安装 Flask:
bash
pip install flask
基本 Flask 应用示例 (app.py):hy029.cn
python
from flask import Flask, jsonify, request
app = Flask(name)
假设的游戏商品列表
games = [
{“id”: 1, “name”: “游戏A”, “price”: 99.99},
{“id”: 2, “name”: “游戏B”, “price”: 149.99}
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games’, methods=[‘POST’])
def add_game():
data = request.get_json()
new_game = {“id”: len(games) + 1, “name”: data[‘name’], “price”: data[‘price’]}
games.append(new_game)
return jsonify(new_game), 201
if name == ‘main’:
app.run(debug=True)
2. JavaScript 使用 Node.js 和 Express
安装 Node.js, Express, 和 body-parser:
bash
npm init -y
npm install express body-parser
Express 应用示例 (app.js):
javascript
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const app = express();
app.use(bodyParser.json());
let games = [
{ id: 1, name: ‘游戏A’, price: 99.99 },
{ id: 2, name: ‘游戏B’, price: 149.99 }
];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.post(‘/games’, (req, res) => {
const newGame = {
id: games.length + 1,
name: req.body.name,
price: req.body.price
};
games.push(newGame);
res.status(201).json(newGame);
});
app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});
3. Java 使用 Spring Boot
设置 Spring Boot 项目(通常使用 Spring Initializr https://start.spring.io/)
Controller 示例 (GameController.java):
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(“/games”)
public class GameController {
private List<Game> games = new ArrayList<>();
{
games.add(new Game(1, "游戏A", 99.99));
games.add(new Game(2, "游戏B", 149.99));
}
@GetMapping
public List<Game> getAllGames() {
return games;
}
@PostMapping
public Game addGame(@RequestBody Game game) {
game.setId(games.size() + 1);
games.add(game);
return game;
}
// Game 类需要被定义,包含 id, name, 和 price 字段
}
class Game {
private int id;
private String name;
private double price;
// 构造函数、getter 和 setter
}
每个示例都提供了一个基本的游戏商品列表管理功能,包括获取所有游戏和添加新游戏。这些示例可以根据需要进行扩展和修改,以适应更复杂的需求。