Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 72 ยท REST APIs

Flask-RESTful and Flask-RESTX Resources

Build REST APIs with Flask-RESTful Api and Resource classes, parse input with reqparse, shape output with fields, then see what Flask-RESTX adds, and when plain MethodView is enough.

In Class-Based Views and MethodView you built resources by hand: one class per URL, one method per HTTP verb. Two well-known extensions wrap that idea with extra conveniences. Flask-RESTful adds an Api object, a Resource base class, request parsing and output shaping. Flask-RESTX is a community fork of Flask-RESTPlus that keeps the same style and adds request validation against declared models plus automatically generated Swagger documentation.

You will meet both of them in many existing codebases, so it is worth knowing how they work, what each one gives you, and why many new projects still pick plain MethodView plus a schema library such as Pydantic (Validation and Serialization).

Install

At home you install the one you need:

TEXT
pip install flask-restful
pip install flask-restx

In the browser editors below, the same packages install with micropip. Do not mix the two in one project; they solve the same problem.

Flask-RESTful: Api and Resource

A Resource is a MethodView subclass: define get, post, put, delete and so on. The Api object registers resources with api.add_resource(Class, url, ...). Three things are different from plain Flask:

  • Return values can be a plain dict, list, or a tuple (data, status, headers). The data is converted to JSON for you, so you do not call jsonify.
  • Errors come from abort(status, message="..."), which produces a JSON body {"message": "..."}.
  • Registration goes through api.add_resource, which also derives endpoint names automatically (the lower-cased class name).
Python Api, Resource and abort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that a missing put gives 405 exactly as it does with MethodView, because Resource is one. The last line shows the automatic endpoint names, booklist and book; pass endpoint="books" to add_resource when you want to choose your own for url_for.

Parsing input with reqparse

reqparse.RequestParser declares which values a request may carry, converts their types and returns a clean dictionary. It can read from the JSON body, the query string, form data or headers through the location argument. When something is missing or has the wrong type, parse_args() stops with a 400 response that lists the problems, so your view code only sees valid data.

Python reqparse: types, required, choices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Things to remember about reqparse:

  • type= can be any callable that turns a string into a value and raises ValueError when it cannot. int, float, bool and your own functions work.
  • required=True and help= produce the error message. inserts the converter's own message.
  • parse_args(strict=True) rejects unknown fields.
  • The Flask-RESTful maintainers mark reqparse as deprecated in their documentation and suggest a library such as Marshmallow or Pydantic for new code. It still works and you will see it everywhere, which is why it is shown here.

Shaping output with fields

Returning raw database objects leaks columns you never meant to publish. fields and marshal_with describe the public shape of a response once: every key you list is read from the returned object (attribute or dictionary key), converted to the declared type and renamed if you ask. Anything else is dropped.

Python marshal_with: the output contract

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

marshal_with is an allowlist: a field you forget to add simply does not appear, which is a safer default than a blocklist. Useful field types are Integer, Float, Boolean, String, DateTime, Nested, List and Url.

Flask-RESTX: models, validation and Swagger

Flask-RESTX keeps the Resource style, adds namespaces (a way to group endpoints) and models you declare with api.model. The same model describes the response (marshal_with), validates the request body (expect(model, validate=True)) and appears in the generated OpenAPI/Swagger document, which also powers the interactive documentation page at / of your API.

Python Flask-RESTX: namespace, model, validation, swagger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The invalid request is rejected before your post runs, and /swagger.json is built from the same declarations. That single source of truth is the main reason teams choose Flask-RESTX.

Which one should you use?

flowchart TD
    A["New REST API in Flask"] --> B{"Need generated<br/>Swagger docs?"}
    B -- yes --> C["Flask-RESTX or an OpenAPI<br/>extension such as flask-smorest"]
    B -- no --> D{"Existing code<br/>uses Flask-RESTful?"}
    D -- yes --> E["Keep it; migrate when you touch it"]
    D -- no --> F["MethodView + Pydantic or Marshmallow"]

A rough guide, not a rule.

  • Plain MethodView + a schema library has the fewest moving parts and the most active ecosystem. It is the default recommendation of this course.
  • Flask-RESTful is small and stable and common in older tutorials and jobs. Its reqparse is deprecated; new code should not depend on it.
  • Flask-RESTX gives you interactive docs and model validation in one package. Check that its release activity meets your needs before betting a long-lived project on it.

All three produce ordinary Flask routes underneath, so error handlers, blueprints and token authentication still apply.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a Flask-RESTful Resource?

    Resource extends MethodView, so each HTTP verb is a method. Api.add_resource registers it at a URL.
  2. 2. What does marshal_with(fields) do to the returned object?

    marshal_with is an allowlist. Undeclared attributes, such as a password hash, are left out of the response.
  3. 3. With reqparse, what happens when a required argument is missing?

    parse_args calls abort(400, ...) with the collected error messages, so the view never runs with invalid input.
  4. 4. Which extra does Flask-RESTX provide compared with Flask-RESTful?

    api.model declarations validate request bodies and feed the /swagger.json document and the interactive docs page.

Summary

  • Flask-RESTful gives you Api, Resource, abort, reqparse and marshal_with; a Resource is a MethodView.
  • reqparse converts and validates input with automatic 400 errors, but is deprecated upstream; fields + marshal_with is an output allowlist.
  • Flask-RESTX adds namespaces, models that validate requests, and Swagger JSON plus a docs page.
  • For new projects, MethodView with Pydantic or Marshmallow is the lean default; keep Flask-RESTful where it already exists.

Next, make the data going in and out of your API reliable with Validation and Serialization.