Leaderboard API Structure

api
└── leaderboard.py # Contains the API routes

model
└── leaderboard.py # Defines the Leaderboard model

main.py # Initializes Flask app

The Model:

We define a table called leaderboard with columns for id, player_name, and score.

The create() method saves a new entry to the database.

The read() method converts the entry into a dictionary (used later to return JSON).

api/leaderboard.py

from flask import Blueprint, request, jsonify
from flask_restful import Api, Resource
from model.leaderboard import LeaderboardEntry

leaderboard_api = Blueprint('leaderboard_api', __name__, url_prefix='/api')
api = Api(leaderboard_api)

Why a Blueprint?

Blueprints helped separate routes into modular files, which keeps code clean and maintainable. We attach the RESTful API to the leaderboard_api blueprint.

POST Method: Submitting a Score

class _CRUD(Resource):
    def post(self):
        data = request.get_json()

        # Extract data and create a new leaderboard entry
        post = LeaderboardEntry(player_name=data['player_name'], score=data['score'])
        post.create()

        return jsonify(post.read())

What It Does: Accepts a JSON payload from the client (like {“player_name”: “Shaurya”, “score”: 88}).

Creates a new LeaderboardEntry and saves it to the database.

Returns the new entry back to the client as JSON.

Example Postman request:

{ “player_name”: “Shaurya”, “score”: 88 }

GET Method: Viewing the Leaderboard

    def get(self):
        try:
            entries = LeaderboardEntry.query.all()
            results = [entry.read() for entry in entries]
            return jsonify(results)
        except Exception as e:
            return jsonify({"error": str(e)}), 500

What It Does:

Queries all rows in the leaderboard table.

Converts them to dictionaries using read().

Returns a JSON list of all scores.


[
  {"id": 1, "player_name": "Shaurya", "score": 88},
  {"id": 2, "player_name": "Jordan", "score": 75}
]

Hooking Up the Endpoint

At the bottom of leaderboard_api.py, we register the resource:

api.add_resource(_CRUD, '/leaderboard')

This makes the /api/leaderboard endpoint available for both GET and POST requests.

Finally, in init.py, don’t forget to register the blueprint:

from api.leaderboard_api import leaderboard_api
app.register_blueprint(leaderboard_api)

Additions

  • Token Authentication: Use @token_required to make score submissions more secure.

  • Timestamps: Add a created_at column to the model to show when the highest scores were achieved.

  • Sorting: Show only the top 10 scores.