What a fascinating python framework!
Published: 2024-05-20 04:44:26

The URL [https://django-ninja.dev/](https://django-ninja.dev/) is the official website of Django-Ninja, a Python web framework for building APIs with Django and Python 3.6+ type hints.

This post is based on the official website of Django Ninja:

Key Features:

Easy: Designed to be easy to use and intuitive.

FAST execution: Very high performance thanks to [Pydantic](https://pydantic-docs.helpmanual.io/) and async support.

Fast to code: Type hints and automatic docs lets you focus only on business logic.

Standards-based: Based on the open standards for APIs: OpenAPI (previously known as
Swagger) and JSON Schema.

Django friendly: (obviously) has good integration with the Django core and ORM.

Production ready: Used by multiple companies on live projects (If you use Django Ninja and
would like to publish your feedback, please email ppr.vitaly@gmail.com).

Other key features:

1. [Async support](https://django-ninja.dev/guides/async-support/) :Django-Ninja integrates
   acync operations, allowing your application to handle multiple requests concurrently. This results in improved performance, scalability, and responsiveness.

2. Django compatibility: Django-Ninja is built on top of Django and inherits many of its features, such as an
   ORM, template engine, and authentication system. This means you can leverage the existing knowledge
   and ecosystem of Django.

3. Micro-architecture: Django-Ninja adopts a micro-architecture approach, which means that your
   application is broken down into smaller, independent components (services). This leads to more
   maintainable, scalable, and flexible code.

4. Type-safe APIs: Django-Ninja uses type-safe APIs, which ensures that your code is more robust and easier
   to maintain. You can define your API endpoints with specific types, making it easier to catch errors and
   improve code quality.

Benefits:

1. Improved performance: With asyncio support, your application can handle multiple requests concurrently,
   reducing the load on your server and improving response times.

2. Better scalability: By using async/await syntax, you can write asynchronous code that's more efficient
   and easier to maintain.

3. Easier development: Django-Ninja's micro-architecture approach makes it easier to develop and maintain
   your application, with smaller, more focused components.

4. Type-safe APIs: The type-safe API ensures that your code is more robust and easier to maintain.
   Who should use Django-Ninja?

    Django-Ninja is suitable for developers who:

    Already have experience with Django or Python web development.

    Are looking for a more modern and efficient alternative to traditional Python web frameworks.

More about Type-safe APIs!

Type-safe APIs are a crucial aspect of Django-Ninja, and they're essential for building robust, maintainable,
and scalable applications. In this section, I'll dive deeper into what type-safe APIs are and how they benefit
your development process.

What are Type-Safe APIs?

Type-safe APIs are a way to define the structure of your API endpoints, including the types of data they
expect and return. In other words, you can specify the types of data that will be sent or received at each
endpoint, ensuring that your code is more robust and easier to maintain.
In Django-Ninja, type-safe APIs are achieved through the use of Python's type hinting system, which allows
you to specify the expected types of function parameters and return values. This enables static type
checking, which can help catch errors early in the development process.

Benefits of Type-Safe APIs:

1. Improved Code Quality: Type-safe APIs ensure that your code is more robust and easier to maintain. By
   specifying the expected types of data, you can catch errors early in the development process, reducing
   the risk of bugs and crashes.
2. Better Error Handling: With type-safe APIs, you can handle errors more effectively. When an error occurs,
   you can pinpoint the exact location and type of error, making it easier to debug and fix issues.
3. Faster Development: Type-safe APIs enable faster development by providing a clear understanding of the
   expected data structures and formats. This reduces the time spent on debugging and troubleshooting.
4. Easier Collaboration: When working with a team, type-safe APIs make it easier to collaborate and share
   code. Everyone can quickly understand the expected data structures and formats, reducing
   misunderstandings and errors.
5. Improved Documentation: Type-safe APIs provide a clear and concise documentation of your API
   endpoints. This makes it easier for developers to understand how to use your API, reducing the need for
   additional documentation.

How do Type-Safe APIs work in Django-Ninja?

In Django-Ninja, you can define type-safe APIs using Python's type hinting system. You can specify the
expected types of function parameters and return values.
For example:

Retrieving Single object 
Suppose we defined a model Employee.
Now to get employee we will define a schema that will describe what our responses will look like.

```py
class EmployeeOut(Schema):
	id: int
	first_name: str
	last_name: str
	department_id: int = None
	birthdate: date = None
```

Defining response schemas are not really required, but when you do define it you will get results validation,
documentation and automatic ORM objects to JSON conversions.

We will use this schema as the response type for our GET employee view:

```py
   @api.get("/employees/{employee_id}", response=EmployeeOut)
   def get_employee(request, employee_id: int):
   	   employee = get_object_or_404(Employee, id=employee_id)
	   return employee
```

Notice that we simply returned an employee ORM object, without a need to convert it to a dict.
The response schema does automatic result validation and conversion to JSON:

```py
@api.get("/employees/{employee_id}", response=EmployeeOut)
def get_employee(request, employee_id: int):
	employee = get_object_or_404(Employee, id=employee_id)
	return employee
```

List of objects
To output a list of employees, we can reuse the same EmployeeOut schema. We will just set the
response schema to a List of EmployeeOut .

```py
from typing import List
@api.get("/employees", response=List[EmployeeOut])
def list_employees(request):
	qs = Employee.objects.all()
	return qs
```

Another cool trick - notice we just returned a Django ORM queryset:
It automatically gets evaluated, validated and converted to a JSON list!

```py
   @api.get("/employees", response=List[EmployeeOut])
   def list_employees(request):
	   qs = Employee.objects.all()
	   return qs
```

In summary, you declare the types of parameters, body, etc. once only, as function parameters.
You do that with standard modern Python types.

You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard Python 3.6+.
For example, for an int :

```py
   a: int
```

or, for a more complex Item model:

```py
class Item(Schema):
	foo: str
	bar: float
def operation(a: Item):

```

... and with that single declaration you get:

Editor support, including:
Completion
Type checks
Validation of data:
Automatic and clear errors when the data is invalid
Validation, even for deeply nested JSON objects

Conversion of input data coming from the network, to Python data and types, and reading from:
JSON
Path parameters
Query parameters
Cookies
Headers
Forms
Files
Automatic, interactive API documentation

What's new in Django Ninja 1.0

Support for Pydantic2
Pydantic version 2 is re-written in Rust and includes a lot of improvements and features like:
Safer types.
Better extensibility.
Better performance

Conclusion:
Django-Ninja is an exciting project that brings together the best of simplicity,
robustness ,power and flexibility. If you're interested in building high-
performance web applications with real-time updates or concurrent processing, Django-Ninja is definitely
worth exploring.