Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

New User Struggling To Get Django Rest Framework JsonAPI Configured To Return A Response In Browser #960

Unanswered
dcs3spp asked this question in Q&A
Discussion options

Hi,

I am a new user struggling to get django-rest_framework-json-api configured to return a response when using the API from a browser.

If I browse to an API endpoint, e.g.
I am receiving the response

{"errors":[{"detail":"invalid query parameter: format","status":"400","source":{"pointer":"/data"},"code":"invalid"}]}

I have listed settings, views etc... below. Can anyone help?

Settings

"""
Django settings for api_proj project.

Generated by 'django-admin startproject' using Django 3.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-$utl*$#frk2uongkclwa@ex4(_r2^&xsje(n+)nlis^%1gbj!&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'api.apps.ApiConfig',
 'rest_framework',
 'rest_framework_json_api',
]
MIDDLEWARE = [
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'api_proj.urls'
TEMPLATES = [
 {
 'BACKEND': 'django.template.backends.django.DjangoTemplates',
 'DIRS': [],
 'APP_DIRS': True,
 'OPTIONS': {
 'context_processors': [
 'django.template.context_processors.debug',
 'django.template.context_processors.request',
 'django.contrib.auth.context_processors.auth',
 'django.contrib.messages.context_processors.messages',
 ],
 },
 },
]
WSGI_APPLICATION = 'api_proj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
 'default': {
 'ENGINE': 'django.db.backends.sqlite3',
 'NAME': BASE_DIR / 'db.sqlite3',
 }
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
 {
 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
 },
 {
 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
 },
 {
 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
 },
 {
 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
 },
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
 'PAGE_SIZE': 10,
 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
 'DEFAULT_PAGINATION_CLASS':
 'rest_framework_json_api.pagination.JsonApiPageNumberPagination',
 'DEFAULT_PARSER_CLASSES': (
 'rest_framework_json_api.parsers.JSONParser',
 'rest_framework.parsers.FormParser',
 'rest_framework.parsers.MultiPartParser'
 ),
 'DEFAULT_RENDERER_CLASSES': (
 'rest_framework_json_api.renderers.JSONRenderer',
 'rest_framework_json_api.renderers.BrowsableAPIRenderer',
 ),
 'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
 'DEFAULT_FILTER_BACKENDS': (
 'rest_framework_json_api.filters.QueryParameterValidationFilter',
 'rest_framework_json_api.filters.OrderingFilter',
 'rest_framework_json_api.django_filters.DjangoFilterBackend',
 'rest_framework.filters.SearchFilter',
 ),
 'SEARCH_PARAM': 'filter[search]',
 'TEST_REQUEST_RENDERER_CLASSES': (
 'rest_framework_json_api.renderers.JSONRenderer',
 ),
 'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json',
}

Serializer

from rest_framework_json_api import serializers
 
from .models import ToDoItem 
class ToDoItemSerializer(serializers.HyperlinkedModelSerializer):
 class Meta: 
 model=ToDoItem 
 fields = ('id', 'name','description')

Model

from django.db import models 
 
class ToDoItem(models.Model): 
 name = models.CharField(max_length=60) 
 description = models.CharField(max_length=500)
 
 def __str__(self): 
 return (
 "TodoItem(\n" 
 f"\tName := {self.name}" 
 f"\n\tDescription := {self.description}"
 "\n)\n"
 )

View

from rest_framework_json_api.views import ModelViewSet
from .models import ToDoItem
from .serializers import ToDoItemSerializer
class ToDoItemViewSet(ModelViewSet):
 queryset = ToDoItem.objects.all().order_by('name')
 serializer_class = ToDoItemSerializer
You must be logged in to vote

Replies: 1 comment 3 replies

Comment options

Hi @dcs3spp and welcome to DJA.

It seems that you hit issue #812

I guess in the browsable api you choose format which then causes this issue. As far as I see by your code snippet is the default JSON:API anyway so no need to choose format.

If this does not work another workaround would be for test cases to temporarily remove rest_framework_json_api.filters.QueryParameterValidationFilter from filter backends to avoid this issue. Hope this helps.

You must be logged in to vote
3 replies
Comment options

Thanks for responding @sliverc, appreciated :)

Yes, it is displaying data using default JSON:API when browsing to an endpoint. When I select a format in the browsable API, issue #812 occurs.

I have tried adding URL_FORMAT_OVERRIDE and setting to contentFormat as shown below. However, #812 still occurs when I choose a format from the browsable API. I get the following error, stating invalid query parameter contentFormat.

{"errors":[{"detail":"invalid query parameter: contentFormat","status":"400","source":{"pointer":"/data"},"code":"invalid"}]}

I have also tried setting URL_FORMAT_OVERRIDE to 'vnd.api%2Bjson' and 'vnd.api'.

Not sure what value I should be setting URL_FORMAT_OVERRIDE to fix #812 here?

REST_FRAMEWORK = {
 'URL_FORMAT_OVERRIDE': 'contentFormat',
 'PAGE_SIZE': 10,
 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
 'DEFAULT_PAGINATION_CLASS':
 'rest_framework_json_api.pagination.JsonApiPageNumberPagination',
 'DEFAULT_PARSER_CLASSES': (
 'rest_framework_json_api.parsers.JSONParser',
 'rest_framework.parsers.FormParser',
 'rest_framework.parsers.MultiPartParser'
 ),
 'DEFAULT_RENDERER_CLASSES': (
 'rest_framework_json_api.renderers.JSONRenderer',
 'rest_framework_json_api.renderers.BrowsableAPIRenderer',
 ),
 'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
 'DEFAULT_FILTER_BACKENDS': (
 'rest_framework_json_api.filters.QueryParameterValidationFilter',
 'rest_framework_json_api.filters.OrderingFilter',
 'rest_framework_json_api.django_filters.DjangoFilterBackend',
 'rest_framework.filters.SearchFilter',
 ),
 'SEARCH_PARAM': 'filter[search]',
 'TEST_REQUEST_RENDERER_CLASSES': (
 'rest_framework_json_api.renderers.JSONRenderer',
 ),
 'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json',
}

If I remove setting URL_FORMAT_OVERRIDE, then browse to the endpoint and choose a format, I receive the following error, stating invalid query parameter: format:

{"errors":[{"detail":"invalid query parameter: format","status":"400","source":{"pointer":"/data"},"code":"invalid"}]}

Removing rest_framework_json_api.filters.QueryParameterValidationFilter from 'DEFAULT_FILTER_BACKENDS allows a response to be returned with link urls that include query parameters:

{"links":{"first":"http://localhost:8000/todos/?contentFormat=vnd.api%2Bjson&page%5Bnumber%5D=1","last":"http://localhost:8000/todos/?contentFormat=vnd.api%2Bjson&page%5Bnumber%5D=1","next":null,"prev":null},"data":[{"type":"ToDoItem","id":"1","attributes":{"name":"#1","description":"Task 1"}},{"type":"ToDoItem","id":"2","attributes":{"name":"#2","description":"Task 2"}},{"type":"ToDoItem","id":"3","attributes":{"name":"#3","description":"Task 3"}},{"type":"ToDoItem","id":"4","attributes":{"name":"#4","description":"Task 4"}},{"type":"ToDoItem","id":"5","attributes":{"name":"#5","description":"Task 5"}}],"meta":{"pagination":{"page":1,"pages":1,"count":5}}}
Comment options

Changing of URL_FORMAT_OVERRIDE will only help once #812 is fixed.

As said this issue only happens with the browsable api when changing format. When the API is actually called by a client the format can easily be changed as per specification.

Comment options

Many thanks @sliverc, appreciated :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /