- Notifications
You must be signed in to change notification settings - Fork302
-
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. {"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, seehttps://docs.djangoproject.com/en/3.2/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/3.2/ref/settings/"""frompathlibimportPath# 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=TrueALLOWED_HOSTS= []# Application definitionINSTALLED_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/#databasesDATABASES= {'default': {'ENGINE':'django.db.backends.sqlite3','NAME':BASE_DIR/'db.sqlite3', }}# Password validation# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validatorsAUTH_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=TrueUSE_L10N=TrueUSE_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-fieldDEFAULT_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 fromrest_framework_json_apiimportserializersfrom .modelsimportToDoItemclassToDoItemSerializer(serializers.HyperlinkedModelSerializer):classMeta:model=ToDoItemfields= ('id','name','description') Model fromdjango.dbimportmodelsclassToDoItem(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 fromrest_framework_json_api.viewsimportModelViewSetfrom .modelsimportToDoItemfrom .serializersimportToDoItemSerializerclassToDoItemViewSet(ModelViewSet):queryset=ToDoItem.objects.all().order_by('name')serializer_class=ToDoItemSerializer |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 1 comment 3 replies
-
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 |
BetaWas this translation helpful?Give feedback.
All reactions
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
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 addingURL_FORMAT_OVERRIDE and setting tocontentFormat as shown below. However,#812 still occurs when I choose a format from the browsable API. I get the following error, statinginvalid query parameter contentFormat. {"errors":[{"detail":"invalid query parameter: contentFormat","status":"400","source":{"pointer":"/data"},"code":"invalid"}]} I have also tried settingURL_FORMAT_OVERRIDE to'vnd.api%2Bjson' and'vnd.api'. Not sure what value I should be settingURL_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 settingURL_FORMAT_OVERRIDE, then browse to the endpoint and choose a format, I receive the following error, statinginvalid query parameter: format: {"errors":[{"detail":"invalid query parameter: format","status":"400","source":{"pointer":"/data"},"code":"invalid"}]} Removing {"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}}} |
BetaWas this translation helpful?Give feedback.
All reactions
-
Changing of 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 perspecification. |
BetaWas this translation helpful?Give feedback.
All reactions
👍 1
-
Many thanks@sliverc, appreciated :) |
BetaWas this translation helpful?Give feedback.