- Python (使用Flask)
app.py
python
from flask import Flask, request, jsonify
app = Flask(name)
games = [
{“id”: 1, “name”: “Game 1”, “price”: 10.99},
{“id”: 2, “name”: “Game 2”, “price”: 20.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):
game = next((item for item in games if item[“id”] == game_id), None)
if game:
return jsonify(game)
else:
return jsonify({“error”: “Game not found”}), 404
更多路由和逻辑…
if name == ‘main’:
app.run(debug=True)
2. JavaScript (使用Node.js和Express)
app.js
javascript
const express = require(‘express’);
const app = express();
const games = [
{id: 1, name: ‘Game 1’, price: 10.99},
{id: 2, name: ‘Game 2’, p#chhas{
margin-top: 50px;
padding:yuhaosujiaofirst.com;
font-size: 18px;
cursor: 10px 20px;
}
rice: 20.99},
// 更多游戏…
];
app.use(express.json());
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const gameId = parseInt(req.params.gameId);
const game = games.find(game => game.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)
GameController.java (仅控制器部分)
java
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping(“/games”)
public class GameController {
private List<Game> games = Arrays.asList(
new Game(1, "Game 1", 10.99),
new Game(2, "Game 2", 20.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 ResourceNotFoundException("Game not found");
}
// 更多方法和逻辑...
// 假设的Game类和ResourceNotFoundException类(你需要自己实现它们)
}
注意:这些示例是非常基础的,并且没有包含完整的错误处理、验证、安全性(如认证和授权)等。在实际项目中,你需要考虑这些因素。此外,为了简洁起见,我省略了数据库交互和其他复杂逻辑。在真实的应用中,你可能需要将这些数据存储在数据库中,并使用ORM(如Hibernate)或其他方法来处理数据库交互。