Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 149 ยท Data and the Web

Flask-RESTful Resources

Build REST APIs with Flask-RESTful. Write Resource classes, route them with Api.add_resource, parse arguments with reqparse, shape output with marshal_with and test everything.

A REST API exposes things (books, users, orders) at URLs and lets clients act on them with HTTP methods: GET to read, POST to create, PUT to replace, DELETE to remove. Plain Flask can do this with decorated functions, as you saw in Project: JSON API with Flask. Flask-RESTful is an extension that adds a small layer on top, built around one idea: each resource is a class, and each HTTP method is a method of that class.

Flask-RESTful gives you three conveniences. Resource classes group the methods for one URL, reqparse validates incoming data, and marshal_with shapes outgoing data. It also turns return values into JSON automatically and answers errors in JSON. This lesson walks through each one using a tiny book collection.

Flask-RESTful is mature and stable, but it is in maintenance mode: it changes slowly and its reqparse module is documented as deprecated in favor of libraries such as marshmallow. You will meet it in many existing code bases, so it is worth knowing. For a new project, consider Flask's built-in MethodView, Flask-Smorest, or FastAPI as well.

Setting up

Neither Flask nor Flask-RESTful is part of the standard library. In the editors on this page you install them with micropip, the in-browser installer (see Packages and pip). The first run downloads the packages and needs an internet connection. On your own computer you would run pip install flask-restful inside a virtual environment and leave the micropip lines out.

A browser tab cannot open a network port, so the examples use Flask's test client. It sends requests straight into your app and returns the responses. Your resources behave exactly as they would behind a real server.

Your first resource

A resource is a subclass of flask_restful.Resource. Define a method named after the HTTP verb (get, post, put, delete) and Flask-RESTful calls it when that kind of request arrives. Then register the class with api.add_resource(ResourceClass, "/url").

Python A first Resource

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.

Several things happened without you writing any code for them:

  • Returning a dictionary produced a JSON response. Returning a tuple (body, status, headers) lets you set the status code and extra headers.
  • /hello/<string:name> is a normal Flask URL rule, and the matched name is passed to get().
  • POST / returned 405 Method Not Allowed with a JSON body, because the Hello class has no post method. You get correct behavior for free just by not defining a method.
  • A URL that no resource claims (/nope) is still answered by Flask itself with an HTML 404 page, which is why get_json() printed None. Flask-RESTful's JSON errors only cover your own routes, so a client that wants JSON for every miss needs a custom 404 handler.

A collection and an item

REST APIs usually come as a pair of URLs: the collection (/books) and a single item (/books/3). In Flask-RESTful that is two resource classes. Here the data lives in a dictionary so we can focus on the API. A database would replace it later, as in Databases with sqlite3.

Python Collection and item resources

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.

Look at what each status code communicates. 201 Created with a Location header says "a new resource now exists at this URL"; 204 No Content says "done, nothing to send back"; 404 and 400 come from abort(...). Flask-RESTful's own abort takes keyword arguments and puts them in the JSON body, so clients get {"message": "..."} instead of an HTML error page.

Validating input with reqparse

In the last example, data["title"] could be a number, a list, or anything else. The reqparse module describes the fields you expect, converts them to the right types and rejects bad requests with a helpful 400 response. Create a RequestParser, add an argument for each field, then call parse_args() inside the method.

Python Parsing and validating arguments

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 string "1965" was converted to the integer 1965; the missing title and the invalid year and rating produced 400 responses that name the problem. By default parse_args() looks in the JSON body, the form and the query string; pass location="json" (or "args", "form", "headers") to an argument to be strict about where it must come from.

Because reqparse is deprecated upstream, new code often validates with marshmallow or Pydantic instead. The pattern stays the same: declare the fields, convert, and reject bad data with a 400 before your logic runs.

Shaping output with marshal_with

Your internal data usually has more fields than the client should see: a password hash, an internal flag, a database-only column. marshal_with takes a dictionary of fields and filters whatever the method returns down to exactly those fields, with consistent types and defaults.

Python Choosing what the client sees

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 works on plain objects and on dictionaries alike. The password_hash attribute is never mentioned in user_fields, so it can never be serialized by accident. A missing value (email=None) becomes the declared default, and fields.Url builds each item's link from its endpoint name, so URLs stay correct if you rename routes.

Organizing a larger API

A few habits keep a Flask-RESTful project tidy:

  • One resource class per URL pattern, in modules grouped by topic. Register them in one place with api.add_resource.
  • Use Api(blueprint) instead of Api(app) to attach your API to a Flask Blueprint, for example under /api/v1.
  • Keep the logic out of the resource. The class translates HTTP into function calls; the real work lives in plain functions or classes you can test without a web server. The inventory project in Project: Inventory Manager shows that separation.
  • Return real status codes and always JSON, so clients never have to parse an HTML error.
  • Test with the test client, as in this lesson, so you do not need a running server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Flask-RESTful, how do you handle GET and DELETE requests for the same URL?

    A Resource class maps each HTTP verb to a method of the same name. Verbs without a method automatically get a 405 response.
  2. 2. What does return book, 201, {"Location": "/books/3"} do inside a resource method?

    A returned tuple is interpreted as (body, status code, headers). The dictionary becomes the JSON body.
  3. 3. What happens when parser.parse_args() receives data that fails validation, such as a year of "abc" for a type=int argument?

    reqparse aborts the request with a 400 Bad Request and a message naming the failing argument, so your method never sees invalid data.
  4. 4. Why is marshal_with useful for security?

    Marshalling is a whitelist: anything not listed in the fields dictionary is left out of the response.
  5. 5. Which description of Flask-RESTful's status is accurate?

    It remains widely used and works, but it receives few updates. For new projects, MethodView, Flask-Smorest or FastAPI are worth considering.

Summary

  • Flask-RESTful organizes an API around Resource classes whose methods (get, post, put, delete) match HTTP verbs; register them with api.add_resource(Class, "/url").
  • Return a dictionary or list for JSON, or a tuple (body, status, headers) to control the response. Use abort(status, message=...) for JSON errors.
  • Use two resources, collection and item, for the usual REST URL pair.
  • reqparse.RequestParser converts and validates incoming arguments and answers bad input with 400; it is deprecated upstream, so know the idea and consider alternatives for new code.
  • marshal_with with a fields dictionary whitelists the output, applies defaults and builds links with fields.Url.
  • Test any Flask app, in the browser or at home, with app.test_client().

Next: NumPy Basics, where the course turns from web APIs to numerical data.