Exceptions - Django REST framework (2023)


Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.

— Doug Hellmann, Python Exception Handling Techniques

Exception handling in REST framework views

REST framework's views handle various exceptions, and deal with returning appropriate error responses.

The handled exceptions are:

  • Subclasses of APIException raised inside REST framework.
  • Django's Http404 exception.
  • Django's PermissionDenied exception.

In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.

Most error responses will include a key detail in the body of the response.

For example, the following request:

DELETE http://api.example.com/foo/bar HTTP/1.1Accept: application/json

Might receive an error response indicating that the DELETE method is not allowed on that resource:

HTTP/1.1 405 Method Not AllowedContent-Type: application/jsonContent-Length: 42{"detail": "Method 'DELETE' not allowed."}

Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting.

An example validation error might look like this:

HTTP/1.1 400 Bad RequestContent-Type: application/jsonContent-Length: 94{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}

Custom exception handling

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.

(Video) Django Rest Framework from Beginner to Advanced (Episode 22 - Exception Handler)

For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:

HTTP/1.1 405 Method Not AllowedContent-Type: application/jsonContent-Length: 62{"status_code": 405, "detail": "Method 'DELETE' not allowed."}

In order to alter the style of the response, you could write the following custom exception handler:

from rest_framework.views import exception_handlerdef custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) #Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response

The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view'].

The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example:

REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'}

If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework:

REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'}

Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.


Signature: APIException()

The base class for all exceptions raised inside an APIView class or @api_view.

To provide a custom exception, subclass APIException and set the .status_code, .default_detail, and default_code attributes on the class.

For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:

from rest_framework.exceptions import APIExceptionclass ServiceUnavailable(APIException): status_code = 503 default_detail = 'Service temporarily unavailable, try again later.' default_code = 'service_unavailable'

Inspecting API exceptions

There are a number of different properties available for inspecting the statusof an API exception. You can use these to build custom exception handlingfor your project.

The available attributes and methods are:

  • .detail - Return the textual description of the error.
  • .get_codes() - Return the code identifier of the error.
  • .get_full_details() - Return both the textual description and the code identifier.

In most cases the error detail will be a simple item:

(Video) Custom Exception Handling. Django Rest Framework Project Tutorial [26]

>>> print(exc.detail)You do not have permission to perform this action.>>> print(exc.get_codes())permission_denied>>> print(exc.get_full_details()){'message':'You do not have permission to perform this action.','code':'permission_denied'}

In the case of validation errors the error detail will be either a list ordictionary of items:

>>> print(exc.detail){"name":"This field is required.","age":"A valid integer is required."}>>> print(exc.get_codes()){"name":"required","age":"invalid"}>>> print(exc.get_full_details()){"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}


Signature: ParseError(detail=None, code=None)

Raised if the request contains malformed data when accessing request.data.

By default this exception results in a response with the HTTP status code "400 Bad Request".


Signature: AuthenticationFailed(detail=None, code=None)

Raised when an incoming request includes incorrect authentication.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.


Signature: NotAuthenticated(detail=None, code=None)

Raised when an unauthenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.


Signature: PermissionDenied(detail=None, code=None)

Raised when an authenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "403 Forbidden".

(Video) Error Handling in Django | Exceptions | Django Rest Framework


Signature: NotFound(detail=None, code=None)

Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception.

By default this exception results in a response with the HTTP status code "404 Not Found".


Signature: MethodNotAllowed(method, detail=None, code=None)

Raised when an incoming request occurs that does not map to a handler method on the view.

By default this exception results in a response with the HTTP status code "405 Method Not Allowed".


Signature: NotAcceptable(detail=None, code=None)

Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers.

By default this exception results in a response with the HTTP status code "406 Not Acceptable".

Signature: UnsupportedMediaType(media_type, detail=None, code=None)

Raised if there are no parsers that can handle the content type of the request data when accessing request.data.

By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".


Signature: Throttled(wait=None, detail=None, code=None)

(Video) Global Exception Handling in Django-rest-framework - Django

Raised when an incoming request fails the throttling checks.

By default this exception results in a response with the HTTP status code "429 Too Many Requests".


Signature: ValidationError(detail, code=None)

The ValidationError exception is slightly different from the other APIException classes:

  • The detail argument is mandatory, not optional.
  • The detail argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the validate() method of a serializer. For example. raise serializers.ValidationError({'name': 'Please enter a valid name.'})
  • By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.')

The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument:


The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.

By default this exception results in a response with the HTTP status code "400 Bad Request".

Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for anAPI-only application.)

Use these as per Django's Customizing error views documentation.


Returns a response with status code 500 and application/json content type.

Set as handler500:

handler500 = 'rest_framework.exceptions.server_error'


Returns a response with status code 400 and application/json content type.

Set as handler400:

(Video) How To Perform Validations In Rest Framework | Django Rest Framework #6

handler400 = 'rest_framework.exceptions.bad_request'

The following third-party packages are also available.

DRF Standardized Errors

The drf-standardized-errors package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.


How do I create a custom exception in Django REST framework? ›

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

What are exceptions in Django? ›

An exception is an abnormal event that leads to program failure. To deal with this situation, Django uses its own exception classes and supports all core Python exceptions as well. Django core exceptions classes are defined in django. core.

How do you handle REST exceptions? ›

Exception Handling for Spring Boot Rest API
  1. Using @ExceptionHandler.
  2. Using @ControllerAdvice.
  3. Using ResponseEntityExceptionHandler Class.
  4. Customizing Exception Handling Using @ResponseStatus.
  5. Handling Exception for Rest API in Practice. Create Custom Error Response. Create Global Exception Handler.
28 Jan 2022

Can we use Django REST framework without Django? ›

REST framework requires the following: Python (3.6, 3.7, 3.8, 3.9, 3.10) Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)

What are the 5 exceptions in selenium? ›

Most Common Selenium Exceptions
  • NoSuchWindowException.
  • NoSuchFrameException.
  • NoSuchElementException.
  • NoAlertPresentException.
  • InvalidSelectorException.
  • TimeoutException.
  • ElementNotVisibleException.
  • ElementNotSelectableException.

What is whitelist in Django? ›

Department of International Trade Django IP Whitelist. A Django middleware to restrict incoming IPs to a Django project to a list of allowed IPs or IP ranges.

What are the 3 types of exceptions? ›

There are three types of exception—the checked exception, the error and the runtime exception.

What are the 3 major exception types in Python? ›

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

What are the two types of exceptions? ›

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception.

What is REST client exception? ›

RestClientException(java.lang.String pMessage) A constructor which takes a message, response object and error code. RestClientException(java.lang.String pMessage, java.lang.Throwable pCause) A constructor which takes a source exception, response object and error code.

What are API exceptions? ›

Exceptions are the errors that happen at runtime. Exception handling is the technique to handle this runtime error in our application code. If any error is thrown in web API that is caught, it is translated into an HTTP response with status code 500- "Internal Server Error". There are many ways to handle the exception.

Which exceptions must be handled? ›

A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn't required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.

Why use Django REST framework instead of Django? ›

Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django. It adopts implementations like class-based views, forms, model validator, QuerySet, and more.

Can I use Django without ORM? ›

Yes that is possible, but a lot of ways how Django can help with webdevelopment are based on its models. For example based on a model Django can make a ModelForm [Django-doc] to automate rendering HTML forms that map to the model, validating user input, and saving it to the database.

What is the difference between Django and Django REST? ›

Django is the web development framework in python whereas the Django Rest Framework is the library used in Django to build Rest APIs. Django Rest Framework is especially designed to make the CRUD operations easier to design in Django. Django Rest Framework makes it easy to use your Django Server as an REST API.

What are common exceptions? ›

Common exception words are important because they are just that: common. They are words that appear frequently in texts and that help readers understand what they are reading. For example, 'the' is a common exception word taught in most programmes at the beginning of the Reception year.

What are all checked exceptions? ›

In general, checked exceptions represent errors outside the control of the program. For example, the constructor of FileInputStream throws FileNotFoundException if the input file does not exist. Java verifies checked exceptions at compile-time.

What does {{ this }} mean in Django? ›

These are special tokens that appear in django templates. You can read more about the syntax at the django template language reference in the documentation. {{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view.

Is allow list same as whitelist? ›

A whitelist (allowlist) is a cybersecurity strategy that approves a list of email addresses, IP addresses, domain names or applications, while denying all others.

Why is whitelist used? ›

The goal of whitelisting is to protect computers and networks from potentially harmful applications. In general, a whitelist is an index of approved entities. In information security (infosec), whitelisting works best in centrally managed environments, where systems are subject to a consistent workload.

What is exception give example? ›

An event that occurs during the execution of a program that disrupts the normal flow of instructions is called an exception. Example: public static void Main ()

What are exceptions four exception types? ›

Checked exceptions
Exception classDescription
ClassNotFoundExceptionThis exception is raised when a class cannot be found.
InstantiationExceptionThis exception is raised when an object cannot be instantiated.
NoSuchMethodExceptionThis exception is raised when a method cannot be found.
2 more rows

How many types of exceptions are there in Python? ›

Python Built-in Exceptions
ExceptionCause of Error
EOFErrorRaised when the input() function hits end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaise when a generator's close() method is called.
ImportErrorRaised when the imported module is not found.
26 more rows

What is difference between error and exception? ›

Both exceptions and errors are the subclasses of a throwable class. The error implies a problem that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur during runtime and compile time.

Is syntax error an exception? ›

An exception caused by the incorrect use of a pre-defined syntax. Syntax errors are detected while compiling or parsing source code.

What are the uses of exceptions? ›

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

What do you mean by exception? ›

: the act of excepting : exclusion. : one that is excepted. especially : a case to which a rule does not apply. 3. : question, objection.

What is double exception? ›

DoubleException happens when an exception happens while handling another exception. So there are two issues here: first is that the panic handler crashes (triggers the DoubleException) and second is that it keeps looping, reentering the panic handler and triggering the exception again.

What are examples of runtime exceptions? ›

The 10 most common examples of RuntimeExceptions in Java are:
  • ArithmeticException.
  • NullPointerException.
  • ClassCastException.
  • DateTimeException.
  • ArrayIndexOutOfBoundsException.
  • NegativeArraySizeException.
  • ArrayStoreException.
  • UnsupportedOperationException.
16 Mar 2022

What are the error codes in REST API? ›

REST API - Response Codes and Statuses
200OKThe request was successfully completed.
201CreatedA new resource was successfully created.
400Bad RequestThe request was invalid.
401UnauthorizedThe request did not include an authentication token or the authentication token was expired.
6 more rows
20 Nov 2019

What are the 4 types of API? ›

There are four principal types of API commonly used in web-based applications: public, partner, private and composite. In this context, the API "type" indicates the intended scope of use.

What are the 6 constraints of rest? ›

The six architectural constraints of REST APIs
  • Client-server architecture. An API's job is to connect two pieces of software without limiting their own functionalities. ...
  • Statelessness. ...
  • Uniform Interface. ...
  • Layered system. ...
  • Cacheability. ...
  • Code on Demand.
22 Jul 2021

What are data exceptions? ›

If we find that something in your data is not correct and we can't start producing your order, we raise an “Exception”. Possible reasons are: the data is not complete – e.g. the drill file is missing. the data is ambiguous – e.g. top and bottom layers are not clearly defined.

What are the 3 blocks used to handle exception? ›

try: Represents a block of code that can throw an exception. catch: Represents a block of code that is executed when a particular exception is thrown. throw: Used to throw an exception.

What are the 3 specific keywords used in exception handling? ›

The exception handling fundamentals in Java revolve around the five keywords- try, catch, finally, throw, and throws. These keywords form the base of exception handling. All the exception handling mechanisms in Java are a result of these five keywords.

Do exceptions have priority? ›

Table 2.16 shows that all exceptions have an associated priority, with: a lower priority value indicating a higher priority. configurable priorities for all exceptions except Reset, HardFault, and NMI.

When should I use Django REST framework? ›

In order to complete your app, if you want to code more python / Django code then use Django, to the contrary if you want to code more JavaScript code then use Django restful API. For web application itself I like using Django ,because it is based on python ,it is much cleaner and shorter than js.

Is Django rest framework a Microservice? ›

This package is built on the djangorestframework-simplejwt package, which provides some JWT authentication mechanisms with Django REST framework.

Why Django is not good for microservices? ›

As the scope of these microservices extended only to information sharing, requirement was for a lighter framework than Django. Django provides a lot of added features — Django ORM, Admin Interface, Authentication/Authorization and so on — which are not really required for this microservice.

Should I use ORM or not? ›

So, do you need an ORM? If you have any more or less complex project and you work with a relational database, then yes, definitely. Big ORMs seem "bloated" not because they are bad tools, but rather because the underlying problem of object-relational mapping is hard.

Is ORM faster than SQL? ›

ORM and SQL are two tools available that web developers can use in database management. When comparing them, SQL has a higher hands-on management than ORM. Because ORM has a higher level of abstraction and more complexity than SQL, less hands-on management is required; this makes data management more efficient.

Is ORM better than stored procedure? ›

Of course, an ORM does not end there, and we can also create other artifacts for stored procedures, etc. We can also merge classes from multiple tables and break a single table into multiple classes. However, the main idea is to use the database mainly as a store and keep all processing logic in the middle-tier code.

What are the disadvantages of REST? ›

Some of the disadvantages of REST are: - Since there is no contract defined between service and client, it has to be communicated through other means such as documentation or emails. - Since it works on HTTP, there can't be asynchronous calls. - Sessions can't be maintained.

Is OData better than REST? ›

OData helps you focus on your business logic while building RESTful APIs without having to worry about the various approaches to define request and response headers, status codes, HTTP methods, URL conventions, media types, payload formats, query options, etc.”

Is Django REST asynchronous? ›

Django has support for writing asynchronous (“async”) views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with performance penalties, and without the ability to have efficient long-running requests.

How do I create a custom exception? ›

Steps to create a Custom Exception with an Example
  1. CustomException class is the custom exception class this class is extending Exception class.
  2. Create one local variable message to store the exception message locally in the class object.
  3. We are passing a string argument to the constructor of the custom exception object.
6 Feb 2020

How can we create custom your own exception exception? ›

To create a custom exception, we have to extend the java. lang. Exception class. Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.

What is a customized exception and how do you implement it? ›

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.

How do I create a custom exception class? ›

In order to create a custom exception, we need to extend the Exception class that belongs to java. lang package. Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.

What are custom exceptions? ›

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.

What is runtime exception? ›

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeException and its subclasses are unchecked exceptions.

What are exceptions in Python? ›

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

When should I create my own exception? ›

Create your own exception types when: you might want to differentiate them when handling.
catch at all instead of letting the exception simply pass through are:
  1. Add some code to make the parent function exception safe. ...
  2. Emit or add some debugging information and rethrow the exception.
  3. Try to recover from the error.
1 Oct 2018

How do I print an exception name? ›

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

Can we create checked exception? ›

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.

What is the purpose of an exception? ›

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

What are 3 basic keywords of exception handling mechanism? ›

Exception handling in C++ consist of three keywords: try , throw and catch : The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error.

What are the four steps of exception handling? ›

  1. try block. The code which can throw any exception is kept inside(or enclosed in) a try block. ...
  2. catch block. catch block is intended to catch the error and handle the exception condition. ...
  3. throw statement. ...
  4. Understanding Need of Exception Handling. ...
  5. Using try , catch and throw Statement. ...
  6. Using Multiple catch blocks.

What are the three major types of exception classes? ›

There are three types of exception—the checked exception, the error and the runtime exception.

What are different types of exception classes? ›

There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.

What are the exception classes? ›

Class Exception. The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.


1. Catch all exceptions in django rest framework - Django
(Solutions Cloud)
2. Django Rest Framework Database Error Exception Handling - Django
(Solutions Cloud)
3. Django : Django Rest Framework Database Error Exception Handling
(Knowledge Base)
4. Override accepted renderer in django-rest-framework on exception - Django
(Solutions Cloud)
5. Django REST Exceptions - Django
(Solutions Cloud)
6. JSON parse error expecting value with Django API #django #freelancejobs #djangorestframework
(Hello World)
Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated: 01/28/2023

Views: 5799

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.