0Pricing
Flask Academy · 课时

资源类与 Api 对象

将端点建模为带动词的资源

资源类与 Api 对象 是 CoddyKit 上的免费 Flask Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flask Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flask Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

A Cleaner Way to Build APIs

Plain Flask routes work, but for APIs Flask-RESTful gives you a tidy, class-based structure that scales as endpoints grow. 🧩

Install the Extension

Flask-RESTful ships separately. Add it to your project with pip before you import anything from it.

pip install flask-restful

Import the Pieces

You need two names: Api, the manager that wires endpoints, and Resource, the base class for each one.

from flask_restful import Api, Resource

Wrap Your App in an Api

Create an Api object around your Flask app. It becomes the registry where every resource gets mounted.

app = Flask(__name__)
api = Api(app)

What a Resource Is

A Resource is a Python class representing one thing in your API, like a task or a user, grouped in one place.

class HelloWorld(Resource):
    pass

Subclass Resource

Every endpoint you build starts by subclassing Resource. Methods inside it will answer HTTP verbs.

class TaskList(Resource):
    def get(self):
        return {"tasks": []}

Mount It on a URL

Use add_resource to attach a resource class to a URL path. That is how the Api learns where it lives.

api.add_resource(TaskList, "/tasks")

Return Plain Dicts

Just return a Python dict and Flask-RESTful serializes it to JSON for you, no manual jsonify needed. ✨

def get(self):
    return {"message": "hello"}

No More Route Decorators

Notice you skipped @app.route entirely. The Api object and add_resource replace the decorator workflow.

Run It Like Any Flask App

Startup is unchanged: the same app.run serves your resource-based API on the dev server.

if __name__ == "__main__":
    app.run(debug=True)

Why Classes Help

Grouping related verbs in one class keeps each endpoint self-contained and far easier to read than scattered functions.

Quick Check

Which object connects a Resource class to a URL?

Recap: Resources and the Api

You wrapped your app in an Api, subclassed Resource, and mounted it with add_resource. A clean API skeleton! 🎉

常见问题解答

「资源类与 Api 对象」课时是免费的吗?

是的 — 「资源类与 Api 对象」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flask Academy 课程的其余内容,请升级到 CoddyKit PRO。 Flask Academy 课程共包含 4 节课。

「资源类与 Api 对象」这节课中我会学到什么?

将端点建模为带动词的资源 你通过在浏览器中直接运行的动手代码来练习 Flask Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flask Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flask Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「资源类与 Api 对象」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flask Academy 课中编写并运行代码吗?

能。每节 Flask Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 资源类与 Api 对象
  2. 将 HTTP 方法映射到类处理器
  3. 使用 reqparse 解析并验证
  4. 挂载在蓝图上的 REST 资源
← 返回 Flask Academy