APIRequestFactory

Creating test requests

The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means the that standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available.

Note: When using APIRequestFactory, the object that is returned is Django's standard HttpRequest, and not REST framework's Request object, which is only generated once the view is called.

This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token directly will have no effect, and setting .user directly will only work if session authentication is being used.

Forcing CSRF validation

By default, requests created with APIRequestFactory will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the enforce_csrf_checks flag when instantiating the factory.

factory = APIRequestFactory(enforce_csrf_checks=True)

Note: It's worth noting that Django's standard RequestFactory doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.

APIClient

Making requests

The APIClient class supports the same request interface as APIRequestFactory. This means the that standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available. For example:

Rendering responses

If you're testing views directly using APIRequestFactory, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access response.content, you'll first need to render the response.

Configuration

Setting the default format

The default format used to make test requests may be set using the TEST_REQUEST_DEFAULT_FORMAT setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your settings.py file:

REST_FRAMEWORK = {
...
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

Setting the available formats

If you need to test requests using something other than multipart or json requests, you can do so by setting the TEST_REQUEST_RENDERER_CLASSES setting.

For example, to add support for using format='yaml' in test requests, you might have something like this in your settings.py file.