- Python (使用 Flask 框架)earnersclub247.com
安装 Flask
bash
pip install Flask
Flask 示例代码
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.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
bash
npm init -y
npm install express body-parser
Express 示例代码
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 需要 Maven 或 Gradle 管理依赖,这里只提供核心代码示例。
Maven 依赖 (pom.xml)
xml
org.springframework.boot
spring-boot-starter-web
Spring Boot 示例代码
java
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<>();
static class Game {
int id;
String name;
double price;
// 构造函数、getter 和 setter 省略
}
@GetMapping
public List<Game> getGames() {
return games;
}
@PostMapping
public Game addGame(@RequestBody Game game) {
game.id = games.size() + 1;
games.add(game);
return game;
}
// 初始化示例数据等逻辑可以放在其他地方
}
以上示例展示了如何在不同的编程语言中实现一个简单的游戏商城API,包括获取游戏列表和添加新游戏的功能。这些示例需要根据你的具体需求进行调整和扩展。