Get Started With Django Ninja: A Beginner's Guide to Building APIs in under 10 Minutes

Опубликовано: 29 Сентябрь 2024
на канале: Vasudev Menon
188
4

Links:
Antares-SQL: https://antares-sql.app/
VS Code: https://code.visualstudio.com/
Django Ninja: https://github.com/vitalik/django-ninja
SQLite: https://www.sqlite.org/index.html
Django: https://www.djangoproject.com/
Pydantic: https://docs.pydantic.dev/latest/
Github Repo:https://github.com/vasudev-gm/django_...
Thumbnail created with FreepikLhttps://www.freepik.com/photo-editor

Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.
Key Features:
• Easy: Designed to be easy to use and intuitive.
• FAST execution: Very high performance thanks to Pydantic 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.

Pydantic is widely used data validation library for python. We can define a schema which has few sets of parameters of different types say int, float str etc. Pydantic makes sure the input/output data is valid without the need to write additional conditions.

Why use Pydantic?
• Type hints
• Speed because it’s written in Rust
• JSON schema
• Strict and Lax mode: strict=True does not convert data while lax=True tries to convert data to the correct when appropriate
• Dataclasses, TypedDicts
• Customisation
• Good Ecosystem
• Battle Tested by Google, Amazon, MSFT,Meta, IBM, Apple etc.
Applications Used:
• VScode 1.81
• DB:SQLite
• Antares 0.7 for viewing and editing DB.
• Django 4.2 LTS
• Django ninja 0.22
• Python 3.11.4 x64 in isolated environment on Windows 10
Schema:
Uses JSON schema by referring the model’s code. We can define a separate input and response schema with all parameters/fields or select few fields.
Once a proper schema is specified, it will ensure only valid datatypes declared for the fields are accepted and invalid input will result in an error.
If you’re coming from flask marshaling, you’ll find it is easier to write and define custom schema and the code is easier to read and debug as well.

I’ve added versioning to the apis and separated v1 and v2 with the paths api/{version_number}/
Just like DRF(Django Rest Framework), you will see automatically generated documentation for your code with OpenAPI 3 fka Swagger and Redoc and it can be accessed in default path api/docs. In my case the docs will be residing under api/v1/docs and api/v2/docs