
REST APIs with Django Ninja in Python
Building REST APIs with Django Ninja in Python
In this tutorial, we will explore how to build REST APIs with Django Ninja, a FastAPI-inspired toolkit for turning Django views into REST API endpoints with minimal extra code.
What is Django Ninja?
Django Ninja is a library that allows you to quickly build API endpoints with Django. It is particularly well-suited for projects that follow the single-page application model, where Django serves as the backend accessed through a REST API. This library simplifies the process of creating endpoints and handling requests and responses.
Getting Started
To get started with Django Ninja, you’ll first need to install it using pip:
pip install django-ninjaNext, let’s create a simple example to demonstrate the use of Django Ninja in building a REST API.
Example: Creating a Simple REST API with Django Ninja
Step 1: Define a Simple API Endpoint
In this example, we will create a simple API endpoint that returns a list of items. First, we need to define the API endpoint using Django Ninja’s APIRouter:
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/items/")
def get_items(request):
items = ["item1", "item2", "item3"]
return {"items": items}In the above code, we define a GET endpoint at the /items/ URL path. When a GET request is made to this endpoint, it returns a JSON response containing a list of items.
Step 2: Run the API Server
To run the API server, we can use Django’s built-in runserver command:
python manage.py runserverNow, if you navigate to http://127.0.0.1:8000/items/ in your web browser or use curl to make a GET request, you will see the JSON response containing the list of items.
Conclusion
In this tutorial, we covered the basics of building REST APIs with Django Ninja in Python. We learned how to define API endpoints and run the API server. Additionally, we explored the simplicity and power of Django Ninja in creating RESTful services with Django. This is just a starting point for working with Django Ninja, and there are many more features and capabilities to explore. Happy coding!





