- Python (使用 Flask)gdtouhaozhoupu.cn
首先,你需要安装 Flask:
bash
pip install flask
然后,可以创建一个简单的 Flask 应用来处理游戏商品的请求:
python
from flask import Flask, jsonify
app = Flask(name)
games = [
{“id”: 1, “name”: “Game of Thrones”, “price”: 59.99},
{“id”: 2, “name”: “Cyberpunk 2077”, “price”: 69.99},
# 更多游戏…
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games), 200
@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), 200
else:
return jsonify({“error”: “Game not found”}), 404
if name == ‘main’:
app.run(debug=True)
2. JavaScript (使用 Node.js 和 Express)
首先,确保安装了 Node.js 和 npm。然后,你可以通过 npm 安装 Express:
bash
npm install express
创建一个简单的 Express 应用:
javascript
const express = require(‘express’);
const app = express();
const port = 3000;
const games = [
{id: 1, name: “Game of Thrones”, price: 59.99},
{id: 2, name: “Cyberpunk 2077”, price: 69.99},
// 更多游戏…
];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const game = games.find(game => game.id === parseInt(req.params.gameId));
if (game) {
res.json(game);
} else {
res.status(404).send({error: ‘Game not found’});
}
});
app.listen(port, () => {
console.log(Game Store API running on port ${port}
);
});
3. Java (使用 Spring Boot)
首先,需要设置 Spring Boot 项目(这通常通过 Spring Initializr 网站或使用 IDE 如 IntelliJ IDEA 来完成)。
下面是一个简单的 Spring Boot 控制器示例:
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@RestController
public class GameController {
private List<Game> games = Arrays.asList(
new Game(1, "Game of Thrones", 59.99),
new Game(2, "Cyberpunk 2077", 69.99)
// 更多游戏...
);
@GetMapping("/games")
public List<Game> getAllGames() {
return games;
}
@GetMapping("/games/{id}")
public Game getGameById(@PathVariable int id) {
return games.stream()
.filter(game -> game.getId() == id)
.findFirst()
.orElseThrow(() -> new RuntimeException("Game not found"));
}
// 假设的 Game 类
static class Game {
private int id;
private String name;
private double price;
Game(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// getters and setters
}
}
请注意,这些示例提供了游戏商城API的基础框架。在真实世界的应用中,你可能需要