1. A
    1. API Blueprint
    2. Addressability
    3. Ajax
    4. Anonymous Function
    5. App Context
  2. B
    1. Blueprint
    2. Business Logic
  3. C
    1. CORS
    2. Callback
    3. Client
    4. Column
    5. Column Attribute
    6. Connectedness
    7. Control
  4. D
    1. DOM
    2. Database Schema
  5. E
    1. Element
    2. Entry Point
  6. F
    1. Fixture
    2. Flask App
    3. Foreign Key
  7. G
    1. Generic Client
  8. H
    1. HTTP Method
    2. HTTP Request
    3. Header
    4. Host Part
    5. Hypermedia
  9. I
    1. Idempotent
    2. Instance Folder
  10. J
    1. JSON
    2. JSON Schema
  11. L
    1. Link Relation
  12. M
    1. MIME Type
    2. Migration
    3. Model Class
  13. N
    1. Namespace
  14. O
    1. ORM
  15. P
    1. Primary Key
    2. Profile
  16. Q
    1. Query
    2. Query Parameter
  17. R
    1. Regular Expression
    2. Request
    3. Request Body
    4. Request Object
    5. Resource
    6. Resource Class
    7. Resource Representation
    8. Response
    9. Response Body
    10. Response Object
    11. Rollback
    12. Routing
    13. Route
    14. Row
  18. S
    1. SQL
    2. Serialization
    3. Static Content
  19. T
    1. Table
    2. Test Setup
    3. Test Teardown
  20. U
    1. URI
    2. URL Template
    3. Uniform Interface
    4. Unique Constraint
  21. V
    1. View Function
    2. Virtualenv
  22. W
    1. Web API
Completed: / exercises

Testing Flask Applications

This page contains information about how to test your
Flask applications
. Testing is divided into two categories: manual testing and unit testing. Manual testing refers to using tools to send
to your API server and examine the
. This is particularly useful during development for
HTTP Methods
other than GET. It allows you to call your
and see what they respond with. Unit testing on the other hand is an important aspect of software engineering, and will be required in the course project. The latter part of this page contains information about writing unit tests.

Running in Debug Mode

When developing, running your application in debug mode is preferable. Being in development mode gives you more detailed output in the server log and enables automatic reloading (i.e. the server restarts whenever changes are detected in files). This is configured by setting the FLASK_ENV environment variable in the shell. In Linux:
export FLASK_ENV=development
In Windows command prompt:
set FLASK_ENV=development
You can also use environment variables to run your app from a Python file that is not named app.py:
export FLASK_APP=sensorhub.py

How to Send POST (and other) Requests

When you type an address into your browser, it always performs a GET
. Your browser does know how to make requests using other methods but doesn't offer a user interface to do so. For instance, when you submit normal HTML forms in web pages, they often perform the submission through a POST request. Unfortunately API servers don't serve HTML forms. But no worries, we can use a browser plugin or Python console to send requests!
Before going through the options, let's setup the up-and-coming sensor hub app to serve the example requests. Download the
from below and start it. Furthermore we're going to assume the database is in the state where we left it, or at least in a state where a sensor called "uo-donkeysensor-1" exists.

Using the Restlet Client

The Talend API Tester is a browser plugin that provides a user interface for sending
HTTP requests
using all
. As the name suggests it's specifically intended for REST APIs, making it very adequate for our purposes. Below is a screenshot of making a simple POST request:
Sending a POST request (partial screenshot)
In addition to sending requests, you can also save them for later use, and organize them neatly into project folders. There's also a request history available at the bottom. This makes it the most recommended option for manual testing.

Using Python Console

Another reasonable way to manually test a
Flask app
is to use the Flask test client inside a Python console session. The same test client feature is used in unit tests, and it's also used by the automated checkers in exercises. Note that the server does not need to be running when using test client. You can obtain a test client by importing your app and calling its test_client method:
In [1]: from app import app
In [2]: client = app.test_client()
The test client object is capable of "sending" "requests" to the server (it actually just creates a
request object
). From your application's viewpoint these are indistinguishable from actual
HTTP requests
. There's a method for each
HTTP method
, e.g. for POST there is client.post. These methods take a number of arguments and keyword arguments - we're only going to cover some of them. The first argument should be the URL, without the
host part
. To get the list of sensors:
In [3]: response = client.get("/sensors/")
In [4]: response.status_code
Out[4]: 200
In [5]: response.data
Out[5]: b'[["uo-donkeysensor-1", "donkeysensor2000"], ["uo-donkeysensor-2", "donkeysensor2000"]]'
Where we can see that the test client returns a
response object
. You can use the dir function to see that it has a whole bunch of attributes. In most cases the interesting ones are status_code and data. Next let's make the same POST request we did with Restlet:
In [6]: response = client.post("/uo-donkeysensor-1/measurements/add/", json={"value": 5.25})
In [7]: response.status_code
Out[7]: 201
An important detail about the test client is that it uses different keyword arguments for different types of data. If your server is implemented to retrieve
data from request.json, then you must use the json keyword when making a request with the test client. Also note that this argument is just a Python data structure. On this course all requests generally use the json keyword for any data that would be in the
request body
. To actually pass the request body as a string, you'd use the data keyword; to pass data that simulates a form submission, you'd use the form keyword (with a dictionary as the value).
In case you need to pass
query parameters
as part of the test request, these go as a dictionary into the query_string keyword argument (NOT in the URL!). For example, calling the trigonometric calculator from console (when in the app folder):
In [1]: from app import app
In [2]: client = app.test_client()
In [3]: response = client.get("/trig/sin", query_string={"angle": 45, "unit": "degree"})
In [4]: response.data
Out[4]: b'0.707'

Unit Testing

The purpose of unit testing is to ensure that individual components of the program behave as they are expected to. A very classic case of unit testing is to test a function with various arguments and comparing its return value(s) to what we expect it to return. As development continues in a project, having tests for each individual component makes it much easier to discover when a change breaks something that worked before. Testing is extremely important for APIs - a popular API is relied upon by numerous web applications that use it. Breaking the API with an untested update can have widespread consequences. Therefore it's integral to ensure that the API works fully before committing changes to a production server.
This section covers the basics of writing unit tests for database

Installation and Setup

We are using pytest in the examples as it is a much leaner framework for testing than Python's built-in unittest module. Its biggest downside is its incompatibility with other testing frameworks, but in this case we don't need those anyway. To install pytest (inside your virtual environment):
pip install pytest
We're also going to install the coverage plugin that can be used to generate reports about the coverage of our tests. It shows which statements in the application source code are covered by our tests. This report will also be used in project evaluation!
pip install pytest-cov
For now let's put our tests into the same directory as our app.py file - we'll do proper project layout later. All Python modules that either begin with test_ or end with _test are automatically detected by pytest. Once you have some tests, you can just type pytest into the terminal when in the project directory to run all tests.

Database Testing

What to Test

One of the benefits of using SQLAlchemy is that we have one less thing to worry about:
. Since SQLAlchemy is a reliable library, we can safely assume that our database queries will work as intended. What we should test however is that our models conform to the intended requirements. The following tests are expected in the course evaluation:
A more thorough checklist would also include (tests for this are shown in the example at the end):

Test Setup

Of course we don't want to run tests on an existing database, and we also don't want tests to interfere with each other. Therefore the first order of business when writing tests for anything related to databases is to create a mechanism that produces a fresh temporary database for each test case. When using pytest, this is best achived with
. A function registered as a fixture is called when executing a test that has the same name as a parameter, i.e.
def my_fixture():
    # do preparations here

def test_something(my_fixture):
    # do some testing
means that when my_test is executed, my_fixture is called first and its return value is accessible with the same name inside the test function. The fixture shown below creates and sets up a new database using a temporary file. It then yields a database handle which test functions can use to perform operations on the database. The code is based on this example.
import os
import pytest
import tempfile

import app

def db_handle():
    db_fd, db_fname = tempfile.mkstemp()
    app.app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_fname
    app.app.config["TESTING"] = True
    with app.app.app_context():
    yield app.db
Implementation detail: Using yield in a fixture enables the same function to handle both
(before yield) and
(after yield). After creating this fixture, your tests can obtain a fresh database by including db_handle in their parameters.
Another thing is to enable foreign key support (like we did in the app itself), and to import all models from the app. Adding these lines after import app does the trick:
from app import Location, Sensor, Deployment, Measurement
from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
After this setup we can do any number of functions whose name starts with test_ and that have db_handle as their sole parameter, e.g. test_create_instances.

Writing Test Functions for Models

A test function represents a test case. It typically consists of preparations and one or more assert statements that are used to determine whether the test subject performed correctly. Assert is a Python statement that functions like an if statement, but instead executing a code block if its condition is (equivalent to) True, assert raises AssertionError if the condition is (equivalent to) False. The pytest framework has its own traceback analysis for AssertionError (see pytest documentation on assert for examples). You can also write a custom message that will replace the traceback.
When testing models a typical pattern is to create one or more model instances, (try to) save them to the database, and then do assertions about the values stored in the database. A simple example related to our sensor app would be to create a sensor with some values, and check that it was stored.
def test_create_sensor(db_handle):
    sensor = Sensor(
    assert Sensor.query.count() == 1
This test will fail if either there is an error in committing the transaction, or if for some reasons there isn't exactly 1 sensor in the database (remember that each test case is run on a fresh empty database). What we'll quickly notice is that the boilerplate code needed to obtain model instances for test cases is repeated a lot. Therefore it's best to create some helper functions that produce these:
def _get_sensor():
    sensor = Sensor(

def test_create_sensor(db_handle):
    sensor = _get_sensor()
    assert Sensor.query.count() == 1
Of course the functions can be parametrized if needed (in the full example at the end of this section some of them have been). A slightly more complex would be to create a sensor and a measurement for it, and assert that the relationship works from both sides:
def _get_sensor():
    sensor = Sensor(

def _get_measurement():
    return Measurement(

def test_create_sensor_measurement(db_handle):
    sensor = _get_sensor()
    measurement = _get_measurement()
    measurement.sensor = sensor
    assert Measurement.query.count() == 1
    assert Sensor.query.count() == 1
    db_measurement = Measurement.query.first()
    db_sensor = Sensor.query.first()
    assert db_measurement.sensor == db_sensor
    assert db_measurement in db_sensor.measurements
There is no need to create separate test functions for creating an instance of each existing model. It's sufficient to gather everything into one function. This has been done in the full example at the end of this section.

Testing Exceptions

Another category of testing is to ensure that certain operations are rejected by the database engine. This would include uniqueness violation as well as
type and restriction violations. Technically it would also include
foreign key
violations. However whether foreign keys work or not has already been tested in the last example - it would fail without properly configured model relationships. The pytest framework has its own mechanism for tests that expect a certain exception to be raised: using pytest.except in a with statement.
Since we are dealing with exceptions, they need to be imported into the test module before they can be referenced. With SQLAlchemy, exceptions are found in the sqlalchemy.exc module (list of exceptions). In our current testing, we need one exception: IntegrityError. To import it:
from sqlalchemy.exc import IntegrityError
For example the following test would check that it's not possible to add two sensors with the same name:
def test_sensor_name_unique(db_handle):
    sensor_1 = _get_sensor()
    sensor_2 = _get_sensor()
    with pytest.raises(IntegrityError):
When testing for exceptions, we are deliberately failing database commits. This puts the database engine into an inconsistent state where it refuses to do further commits - trying to do so results in InvalidRequestError. In order to be able to continue testing in the same function after a deliberate failure, a
is needed. A rollback cancels everything that was queued up for the failed commit. This is done by calling the rollback method of the database session, e.g. db_handle.session.rollback(). This has been done in the full test example.

Documenting Tests

If you have run any of the tests introduced so far, you may have noticed that pytest doesn't have particularly much to say about tests that pass - not even their names in the output. In order to actually remember in the future what the gazillion tests you wrote a year ago do, this information needs to be written somewhere. A good practice is to write each test function's purpose in its documentation string. Furthermore, if the test function is long and has multiple phases, these should be annotated with normal comments in the function source code.
On this course in particular, the value of your tests is based on your documentation. If you haven't documented a test, we're going to assume the test does not exist when evaluating your tests.

Model Testing Example

Below is a full example test for our sensorhub application. Do note that this example contains more meticulous testing than is required from your project. You don't need to test things like column types or nullable columns in your project. They are just shown here for completeness' sake.
Drop the test module into the same folder as your app and run it by typing pytest. Do note that you may get 3 deprecation warnings related to Werkzeug (about importing ABC from collections). These can be ignored, as they are not your fault. Hopefully a Werkzeug developer will catch onto them before Python 3.8 is released...
If you want to check the coverage then use pytest --cov=myproject where myproject is the location of your flask project.
API Blueprint is a description language for REST APIs. Its primary categories are resources and their related actions (i.e. HTTP methods). It uses a relatively simple syntax. The advantage of using API Blueprint is the wide array of tools available. For example Apiary has a lot of features (interactive documentation, mockup server, test generation etc.) that can be utilized if the API is described in API Blueprint.
Another widely used alteranative for API Blueprint is OpenAPI.
Addressability is one of the key REST principles. It means that in an API everything should be presented as resources with URIs so that every possible action can be given an address. On the flipside this also means that every single address should always result in the same resource being accessed, with the same parameters. From the perspective of addressability, query parameters are part of the address.
Ajax is a common web technique. It used to be known as AJAX, an acronym for Asynchronous Javascript And XML but with JSON largely replacing XML, it become just Ajax. Ajax is used in web pages to make requests to the server without a page reload being triggered. These requests are asynchronous - the page script doesn't stop to wait for the response. Instead a callback is set to handle the response when it is received. Ajax can be used to make a request with any HTTP method.
  1. Description
  2. Examples
Anonymous functions are usually used as in-place functions to define a callback. They are named such because they are defined just like functions, but don't have a name. In JavaScript function definition returns the function as an object so that it can e.g. passed as an argument to another function. Generally they are used as one-off callbacks when it makes the code more readable to have the function defined where the callback is needed rather than somewhere else. A typical example is the forEach method of arrays. It takes a callback as its arguments and calls that function for each of its members. One downside of anonymous functions is that they function is defined anew every time, and this can cause significant overhead if performed constantly.
  1. Description
  2. Example
In Flask application context (app context for short) is an object that keeps tracks of application level data, e.g. configuration. You always need to have it when trying to manipulate the database etc. View functions will automatically have app context included, but if you want to manipulate the database or test functions from the interactive Python console, you need to obtain app context using a with statement.
Blueprint is a Flask feature, a way of grouping different parts of the web application in such a way that each part is registered as a blueprint with its own root URI. Typical example could be an admin blueprint for admin-related features, using the root URI /admin/. Inside a blueprint, are routes are defined relatively to this root, i.e. the route /users/ inside the admin blueprint would have the full route of /admin/users/.
Defines how data is processed in the application
Cross Origin Resource Sharing (CORS) is a relaxation mechanism for Same Origin Policy (SOP). Through CORS headers, servers can allow requests from external origins, what can be requested, and what headers can be included in those requests. If a server doesn't provide CORS headers, browsers will browsers will apply the SOP and refuse to make requests unless the origin is the same. Note that the primary purpose of CORS is to allow only certain trusted origins. Example scenario: a site with dubious script cannot just steal a user's API credentials from another site's cookies and make requests using them because the APIs CORS configuration doesn't allow requests from the site's origin. NOTE: this is not a mechanism to protect your API, it's to protect browser users from accessing your API unintentionally.
Callback is a function that is passed to another part of the program, usually as an argument, to be called when certain conditions are met. For instance in making Ajax requests, it's typical to register a callback for at least success and error situations. A typical feature of callbacks is that the function cannot decide its own parameters, and must instead make do with the arguments given by the part of the program that calls it. Callbacks are also called handlers. One-off callbacks are often defined as anonymous functions.
Piece of software that consumes or utilizes the functionality of a Web API. Some clients are controlled by humans, while others (e.g. crawlers, monitors, scripts, agents) have different degree of autonomy.
In databases, columns define the attributes of objects stored in a table. A column has a type, and can have additional properties such as being unique. If a row doesn't conform with the column types and other restrictions, it cannot be inserted into the table.
  1. Description
  2. Common keywords
In object relational mapping, column attributes are attributes in model classes that have been initialized as columns (e.g. in SQLAlchemy their initial value is obtained by initializing a Column). Each of these attributes corresponds to a column in the database table (that corresponds with the model class). A column attribute defines the column's type as well as additional properties (e.g. primary key).
Connectedness is a REST principle particularly related to hypermedia APIs. It states that there for each resource in the API, there must exist a path from every other resource to get there by following hypermedia links. Connectedness is easiest to analyze by creating an API state diagram.
  1. Description
  2. Example
A hypermedia control is an attribute in a resource representation that describes a possible action to the client. It can be a link to follow, or an action that manipulates the resource in some way. Regardless of the used hypermedia format, controls include at least the URI to use when performing the action. In Mason controls also include the HTTP method to use (if it's not GET), and can also include a schema that describes what's considered valid for the request body.
Document Object Model (DOM) is an interface through which Javascript code can interact with the HTML document. It's a tree structure that follows the HTML's hierarchy, and each HTML tag has its own node. Through DOM manipulation, Javascript code can insert new HTML into anywhere, modify its contents or remove it. Any modifications to the DOM are updated into the web page in real time. Do note that since this is a rendering operation, it's very likely one of the most costly operations your code can do. Therefore changing the entire contents of an element at once is better than changing it e.g. one line at a time.
Database schema is the "blueprint" of the database. It defines what tables are contained in the database, and what columns are in each table, and what additional attributes they have. A database's schema can be dumped into an SQL file, and a database can also be created from a schema file. When using object relational mapping (ORM), the schema is constructed from model classes.
In HTML element refers to a single tag - most of the time including a closing tag and everything in between. The element's properties are defined by the tag, and any of the properties can be used to select that element from the document object model (DOM). Elements can contain other elements, which forms the HTML document's hierarchy.
For APIs entry point is the "landing page" of the API. It's typically in the API root of the URL hierarchy and contains logical first steps for a client to take when interacting with the API. This means it typically has one or more hypermedia controls which usually point to relevant collections in the API or search functions.
In software testing, a fixture is a component that satisfies the preconditions required by tests. In web application testing the most common role for fixtures is to initialize the database into a state that makes testing possible. This generally involves creating a fresh database, and possibly populating it with some data. In this course fixtures are implemented using pytest's fixture architecture.
  1. Description
  2. Creating DB
  3. Starting the App
This term contains basic instructions about setting up and running Flask applications. See the term tabs "Creating DB" and "Starting the App". For all instructions to work you need to be in the folder that contains your app.
In database terminology, foreign key means a column that has its value range determined by the values of a column in another table. They are used to create relationships between tables. The foreign key column in the target table must be unique.
For most hypermedia types, there exists a generic client. This is a client program that constructs a navigatable user interface based on hypermedia controls in the API, and can usually also generate data input forms. The ability to use such clients for testing and prototyping is one of the big advantages of hypermedia.
HTTP method is the "type" of an HTTP request, indicating what kind of an action the sender is intending to do. In web applications by far the most common method is GET which is used for retrieving data (i.e. HTML pages) from the server. The other method used in web applications is POST, used in submitting forms. However, in REST API use cases, PUT and DELETE methods are also commonly used to modify and delete data.
HTTP request is the entirety of the requets made by a client to a server using the HTTP protocol. It includes the request URL, request method (GET, POST etc.), headers and request body. In Python web frameworks the HTTP request is typically turned into a request object.
Headers are additional information fields included in HTTP requests and responses. Typical examples of headers are content-type and content-length which inform the receiver how the content should be interpreted, and how long it should be. In Flask headers are contained in the request.headers attribute that works like a dictionary.
Host part is the part of URL that indicates the server's address. For example, lovelace.oulu.fi is the host part. This part determines where (i.e. which IP address) in the world wide web the request is sent.
In API terminology hypermedia means additional information that is added on top of raw data in resource representations. It's derived from hypertext - the stuff that makes the world wide web tick. The purpose of the added hypermedia is to inform the client about actions that are available in relation to the resource they requested. When this information is conveyed in the representations sent by the API, the client doesn't need to know how to perform these actions beforehand - it only needs to parse them from the response.
An idempotent operation is an operation that, if applied multiple times with the same parameters, always has the same result regardless of how many times it's applied. If used properly, PUT is an idempotent operation: no matter how many times you replace the contents of a resource it will have the same contents as it would have if only one request had been made. On the other hand POST is usually not idempotent because it attempts to create a new resource with every request.
Instance folder is a Flask feature. It is intended for storing files that are needed when running the Flask application, but should not be in the project's code repository. Primary example of this is the prodcution configuration file which differs from installation to installation, and generally should remain unchanged when the application code is updated from the repository. The instance path can be found from the application context: app.instance_path. Flask has a reasonable default for it, but it can also be set manually when calling Flask constuctor by adding the instance_path keyword argument. The path should be written as absolute in this case.
  1. Description
  2. Serializing / Parsing
JavaScript Object Notation (JSON) is a popular document format in web development. It's a serialized representation of a data structure. Although the representation syntax originates from JavaScript, It's almost identical to Python dictionaries and lists in formatting and structure. A JSON document conists of key-value pairs (similar to Python dictionaries) and arrays (similar to Python lists). It's often used in APIs, and also in AJAX calls on web sites.
JSON schema is a JSON document that defines the validity criteria for JSON documents that fall under the schema. It defines the type of the root object, and types as well as additional constraints for attributes, and which attributes are required. JSON schemas serve two purposes in this course: clients can use them to generate requests to create/modify resources, and they can also be used on the API end to validate incoming requests.
  1. Description
  2. Common MIME types
MIME type is a standard used for indicating the type of a document.In web development context it is placed in the Content-Type header. Browsers and servers the MIME type to determine how to process the request/response content. On this course the MIME type is in most cases application/json.
Database migration is a process where an existing database is updated with a new database schema. This is done in a way that does not lose data. Some changes can be migrated automatically. These include creation of new tables, removal of columns and adding nullable columns. Other changes often require a migration script that does the change in multiple steps so that old data can be transformed to fit the new schema. E.g. adding a non-nullable column usually involves adding it first as nullable, then using a piece of code to determine values for each row, and finally setting the column to non-nullable.
  1. Description
  2. Example
In ORM terminology, a model class is a program level class that represents a database table. Instances of the class represent rows in the table. Creation and modification operations are performed using the class and instances. Model classes typically share a common parent (e.g. db.Model) and table columns are defined as class attributes with special constuctors (e.g. db.Column).
  1. Description
  2. Example
In API terminology, namespace is a prefix for names used by the API that makes them unique. The namespace should be a URI, but it doesn't have to be a real address. However, usually it is convenient to place a document that described the names within the namespace into the namespace URI. For our purposes, namespace contains the custom link relations used by the API.
Object relational mapping is a way of abstracting database use. Database tables are mapped to programming language classes. These are usually called models. A model class declaration defines the table's structure. When rows from the database table are fetched, they are represented as instances of the model class with columns as attributes. Likewise new rows are created by making new instances of the model class and committing them to the database. This course uses SQLAlchemy's ORM engine.
In database terminology primary key refers to the column in a table that's intended to be the primary way of identifying rows. Each table must have exactly one, and it needs to be unique. This is usually some kind of a unique identifier associated with objects presented by the table, or if such an identifier doesn't exist simply a running ID number (which is incremented automatically).
Profile is metadata about a resource. It's a document intended for client developers. A profile gives meaning to each word used in the resource representation be it link relation or data attribute (also known as semantic descriptors). With the help of profiles, client developers can teach machine clients to understand resource representations sent by the API. Note that profiles are not part of the API and are usually served as static HTML documents. Resource representations should always contain a link to their profile.
In database terminology, query is a command sent to the database that can fetch or alter data in the database. Queries use written with a script-like language. Most common is the structured query language (SQL). In object relational mapping, queries are abstracted behind Python method calls.
  1. Description
  2. Example
Query parameters are additional parameters that are included in a URL. You can often see these in web searches. They are the primary mechanism of passing arbitrary parameters with an HTTP request. They are separated from the actual address by ?. Each parameter is written as a key=value pair, and they are separated from each other by &. In Flask applications they can be found from request.args which works like a dictionary.
  1. Description
  2. Examples
Regular expressions are used in computing to define matching patterns for strings. In this course they are primarily used in validation of route variables, and in JSON schemas. Typical features of regular expressions are that they look like a string of garbage letters and get easily out of hand if you need to match something complex. They are also widely used in Lovelace text field exercises to match correct (and incorrect) answers.
In this course request referes to HTTP request. It's a request sent by a client to an HTTP server. It consists of the requested URL which identifies the resource the client wants to access, a method describing what it wants to do with the resource. Requests also include headers which provide further context information, and possihby a request body that can contain e.g. a file to upload.
  1. Description
  2. Accessing
In an HTTP request, the request body is the actual content of the request. For example when uploading a file, the file's contents would be contained within the request body. When working with APIs, request body usually contains a JSON document. Request body is mostly used with POST, PUT and PATCH requests.
  1. Description
  2. Getting data
Request object is related to web development frameworks. It's a programming language object representation of the HTTP request made to the server. It has attributes that contain all the information contained within the request, e.g. method, url, headers, request body. In Flask the object can be imported from Flask to make it globally available.
in RESTful API terminology, a resource is anything that is interesting enough that a client might want to access it. A resource is a representation of data that is stored in the API. While they usually represent data from the database tables it is important to understand that they do not have a one-to-one mapping to database tables. A resource can combine data from multiple tables, and there can be multiple representations of a single table. Also things like searches are seen as resources (it does, after all, return a filtered representation of data).
Resource classes are introduced in Flask-RESTful for implementing resources. They are inherited from flask_restful.Resource. A resource class has a view-like method for each HTTP method supported by the resource (method names are written in lowercase). Resources are routed through api.add_resource which routes all of the methods to the same URI (in accordance to REST principles). As a consequence, all methods must also have the same parameters.
In this course we use the term representation to emphasize that a resource is, in fact, a representation of something stored in the API server. In particular you can consider representation to mean the response sent by the API when it receives a GET request. This representation contains not only data but also hypermedia controls which describe the actions available to the client.
In this course response refers to HTTP response, the response given by an HTTP server when a request is made to it. Reponses are made of a status code, headers and (optionally) response body. Status code describes the result of the transaction (success, error, something else). Headers provide context information, and response body contains the document (e.g. HTML document) returned by the server.
Response body is the part of HTTP response that contains the actual data sent by the server. The body will be either text or binary, and this information with additional type instructions (e.g. JSON) are defined by the response's Content-type header. Only GET requests are expected to return a response body on a successful request.
Response object is the client side counterpart of request object. It is mainly used in testing: the Flask test client returns a response object when it makes a "request" to the server. The response object has various attributes that represent different parts of an actual HTTP response. Most important are usually status_code and data.
In database terminology, rollback is the cancellation of a database transaction by returning the database to a previous (stable) state. Rollbacks are generally needed if a transaction puts the database in an error state. On this course rollbacks are generally used in testing after deliberately causing errors.
  1. Description
  2. Routing in Flask
  3. Reverse routing
  4. Flask-RESTful routing
URL routing in web frameworks is the process in which the framework transforms the URL from an HTTP request into a Python function call. When routing, a URL is matched against a sequence of URL templates defined by the web application. The request is routed to the function registered for the first matching URL template. Any variables defined in the template are passed to the function as parameters.
In relational database terminology, row refers to a single member of table, i.e. one object with properties that are defined by the table's columns. Rows must be uniquely identifiable by at least one column (the table's primary key).
SQL (structured query language) is a family of languages that are used for interacting with databases. Queries typically involve selecting a range of data from one or more tables, and defining an operation to perform to it (such as retrieve the contents).
Serialization is a common term in computer science. It's a process through which data structures from a program are turned into a format that can be saved on the hard drive or sent over the network. Serialization is a reversible process - it should be possible to restore the data structure from the representation. A very common serialization method in web development is JSON.
In web applications static content refers to content that is served from static files in the web server's hard drive (or in bigger installations from a separate media server). This includes images as well as javascript files. Also HTML files that are not generated from templates are static content.
In database terminology, a table is a collection of similar items. The attributes of those items are defined by the table's columns that are declared when the table is created. Each item in a table is contained in a row.
In software testing, test setup is a procedure that is undertaken before each test case. It prepares preconditions for the test. On this course this is done with pytest's fixtures.
In software testing, test teardown is a process that is undertaken after each test case. Generally this involves clearing up the database (e.g. dropping all tables) and closing file descriptors, socket connections etc. On this course pytest fixtures are used for this purpose.
Universal resource identifier (URI) is basically what the name says: it's a string that unambiguously identifies a resource, thereby making it addressable. In APIs everything that is interesting enough is given its own URI. URLs are URIs that specify the exact location where to find the resource which means including protocol (http) and server part (e.g. lovelace.oulu.fi) in addition to the part that identifies the resource within the server (e.g. /ohjelmoitava-web/programmable-web-project-spring-2019).
  1. Description
  2. Type converters
  3. Custom converters
URL template defines a range of possible URLs that all lead to the same view function by defining variables. While it's possible for these variables to take arbitrary values, they are more commonly used to select one object from a group of similar objects, i.e. one user's profile from all the user profiles in the web service (in Flask: /profile/<username>. If a matching object doesn't exist, the default response would be 404 Not Found. When using a web framework, variables in the URL template are usually passed to the corresponding view function as arguments.
Uniform interface is a REST principle which states that all HTTP methods, which are the verbs of the API, should always behave in the same standardized way. In summary:
  • GET - should return a representation of the resource; does not modify anything
  • POST - should create a new instance that belongs to the target collection
  • PUT - should replace the target resource with a new representation (usually only if it exists)
  • DELETE - should delete the target resource
  • PATCH - should describe a change to the resource
In database terminology, unique constraint is a what ensures the uniqueness of each row in a table. Primary key automatically creates a unique constraint, as do unique columns. A unique constraint can also be a combination of columns so that each combination of values between these columns is unique. For example, page numbers by themselves are hardly unique as each book has a first page, but a combination of book and page number is unique - you can only have one first page in a book.
  1. Description
  2. Registering
View functions are Python functions (or methods) that are used for serving HTTP requests. In web applications that often means rendering a view (i.e. a web page). View functions are invoked from URLs by routing. A view function always has application context.
  1. Description
  2. Creation
  3. Activation
A Python virtual environment (virtualenv, venv) is a system for managing packages separately from the operating system's main Python installation. They help project dependency management in multiple ways. First of all, you can install specific versions of packages per project. Second, you can easily get a list of requirements for your project without any extra packages. Third, they can placed in directories owned by non-admin users so that those users can install the packages they need without admin privileges. The venv module which is in charge of creating virtual environments comes with newer versions of Python.
Interface, implemented using web technologies, that exposes a functionality in a remote machine (server). By extension Web API is the exposed functionality itself.