- Python (使用Flask框架)gdtouhaozhoupu.cn
python
from flask import Flask, request, jsonify
app = Flask(name)
模拟游戏商品列表
games = [
{“id”: 1, “name”: “Game A”, “price”: 9.99},
{“id”: 2, “name”: “Game B”, “price”: 19.99},
# … 更多游戏
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
for game in games:
if game[‘id’] == game_id:
return jsonify(game)
return jsonify({‘error’: ‘Game not found’}), 404
启动Flask应用
if name == ‘main’:
app.run(debug=True)
2. JavaScript (使用Node.js和Express框架)
javascript
const express = require(‘express’);
const app = express();
app.use(express.json());
// 模拟游戏商品列表
const games = [
{id: 1, name: ‘Game A’, price: 9.99},
{id: 2, name: ‘Game B’, price: 19.99},
// … 更多游戏
];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const gameId = parseInt(req.params.gameId);
const game = games.find(g => g.id === gameId);
if (game) {
res.json(game);
} else {
res.status(404).json({error: ‘Game not found’});
}
});
app.listen(3000, () => console.log(‘Server started on port 3000’));
3. Java (使用Spring Boot框架)
Java示例会更长且需要更多的文件结构,但这里是一个简单的Controller类示例:
java
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping(“/games”)
public class GameController {
// 模拟游戏商品列表
private static final List<Game> games = Arrays.asList(
new Game(1, "Game A", 9.99),
new Game(2, "Game B", 19.99)
// ... 更多游戏
);
@GetMapping
public List<Game> getGames() {
return games;
}
@GetMapping("/{gameId}")
public Game getGame(@PathVariable int gameId) {
for (Game game : games) {
if (game.getId() == gameId) {
return game;
}
}
throw new RuntimeException("Game not found");
}
// 简单的Game类(你需要定义它)
static class Game {
private int id;
private String name;
private double price;
// 构造函数、getter和setter...
}
}
请注意,这些示例仅用于展示如何在不同编程语言中构建基本的RESTful API来模拟游戏商城的功能。在实际应用中,你需要考虑更多的因素,如安全性、性能优化、数据库集成等。