- Python (Flask)cnavmall.cn
假设你使用Flask框架来创建一个简单的REST API。
python
from flask import Flask, request, jsonify
app = Flask(name)
模拟的游戏商品数据
games = [
{“id”: 1, “name”: “Cyberpunk 2077”, “price”: 59.99},
{“id”: 2, “name”: “The Witcher 3”, “price”: 29.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)
使用Node.js和Express框架创建API。
javascript
const express = require(‘express’);
const app = express();
const games = [
{id: 1, name: “Cyberpunk 2077”, price: 59.99},
{id: 2, name: “The Witcher 3”, price: 29.99}
];
app.use(express.json());
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:game_id’, (req, res) => {
const game = games.find(game => game.id === parseInt(req.params.game_id));
if (game) {
res.json(game);
} else {
res.status(404).json({error: “Game not found”});
}
});
app.listen(3000, () => {
console.log(‘Game Store API listening on port 3000’);
});
3. Java (Spring Boot)
在Spring Boot中,你可能会有一个GameController类来处理HTTP请求。
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, "Cyberpunk 2077", 59.99),
new Game(2, "The Witcher 3", 29.99)
);
@GetMapping
public List<Game> getAllGames() {
return games;
}
@GetMapping("/{id}")
public Game getGameById(@PathVariable Long id) {
return games.stream()
.filter(game -> game.getId().equals(id))
.findFirst()
.orElseThrow(() -> new RuntimeException("Game not found"));
}
// 假设Game是一个简单的POJO类
static class Game {
private Long id;
private String name;
private Double price;
// 构造函数、getter和setter省略
}
}
请注意,这些示例只是API接口的设计,不包括数据库交互、安全性、错误处理、日志记录等生产环境中必要的元素。对于完整的游戏商城系统,你还需要考虑用户认证、支付集成、库存管理等多个方面。