Convert Figma logo to code with AI

encode logodjango-rest-framework

Web APIs for Django. 🎸

28,116
6,803
28,116
89

Top Related Projects

79,088

The Web framework for perfectionists with deadlines.

67,504

The Python micro framework for building web applications.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

21,674

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

14,938

Asynchronous HTTP client/server framework for asyncio and Python

64,773

Fast, unopinionated, minimalist web framework for node.

Quick Overview

Django REST framework is a powerful and flexible toolkit for building Web APIs in Django. It provides a set of tools and utilities that make it easy to create RESTful APIs, including serialization, authentication, and pagination. The framework is widely used in the Django community for building robust and scalable API-driven applications.

Pros

  • Extensive documentation and strong community support
  • Browsable API for easy testing and debugging
  • Flexible authentication and permission systems
  • Seamless integration with Django's ORM and other features

Cons

  • Steeper learning curve for beginners compared to simpler alternatives
  • Can be overkill for small projects or simple APIs
  • Performance overhead due to its extensive feature set
  • Some customizations may require diving deep into the framework's internals

Code Examples

  1. Creating a simple API view:
from rest_framework.views import APIView
from rest_framework.response import Response

class HelloWorldView(APIView):
    def get(self, request):
        return Response({"message": "Hello, World!"})
  1. Serializing a model:
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']
  1. Using viewsets for CRUD operations:
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Getting Started

  1. Install Django REST framework:
pip install djangorestframework
  1. Add 'rest_framework' to INSTALLED_APPS in your Django settings:
INSTALLED_APPS = [
    ...
    'rest_framework',
]
  1. Create a serializer for your model:
from rest_framework import serializers
from .models import YourModel

class YourModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = YourModel
        fields = '__all__'
  1. Create a view or viewset:
from rest_framework import viewsets
from .models import YourModel
from .serializers import YourModelSerializer

class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
  1. Configure URLs in your urls.py:
from rest_framework.routers import DefaultRouter
from .views import YourModelViewSet

router = DefaultRouter()
router.register(r'yourmodel', YourModelViewSet)

urlpatterns = [
    ...
    path('api/', include(router.urls)),
]

Competitor Comparisons

79,088

The Web framework for perfectionists with deadlines.

Pros of Django

  • Full-featured web framework with built-in admin interface, ORM, and authentication
  • Larger community and ecosystem with more third-party packages
  • Comprehensive documentation and tutorials for beginners

Cons of Django

  • Steeper learning curve for newcomers to web development
  • Can be overkill for smaller projects or APIs
  • Less flexibility in customizing the core framework

Code Comparison

Django (URL routing):

urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
]

Django REST framework (API view):

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]

Django REST framework is built on top of Django, providing powerful tools for building Web APIs. It offers serialization, authentication, and viewsets specifically designed for RESTful interfaces. While Django is a complete web framework, Django REST framework focuses on API development, making it more suitable for projects that primarily serve as backends for mobile or single-page applications.

67,504

The Python micro framework for building web applications.

Pros of Flask

  • Lightweight and minimalist, allowing for more flexibility and customization
  • Easier to get started with for small projects or microservices
  • Better performance for simple applications due to less overhead

Cons of Flask

  • Lacks built-in features, requiring additional extensions for common functionalities
  • Less opinionated, which can lead to inconsistent code structure across projects
  • Smaller ecosystem compared to Django REST Framework

Code Comparison

Flask:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/users')
def get_users():
    users = [{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Jane'}]
    return jsonify(users)

Django REST Framework:

from rest_framework.views import APIView
from rest_framework.response import Response

class UserList(APIView):
    def get(self, request):
        users = [{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Jane'}]
        return Response(users)

Both frameworks allow for creating API endpoints, but Flask's approach is more straightforward for simple cases, while Django REST Framework provides a more structured and feature-rich environment for building complex APIs.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • Faster performance due to asynchronous capabilities
  • Built-in API documentation with Swagger UI and ReDoc
  • Type hints and automatic data validation

Cons of FastAPI

  • Smaller ecosystem and community compared to Django REST Framework
  • Less mature and fewer third-party packages available
  • Steeper learning curve for developers new to async programming

Code Comparison

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Django REST Framework:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def hello_world(request):
    return Response({"message": "Hello World"})

FastAPI offers a more concise syntax and built-in async support, while Django REST Framework provides a familiar structure for Django developers. FastAPI's type hinting and automatic documentation generation simplify API development, but Django REST Framework benefits from Django's extensive ecosystem and mature tooling. The choice between the two depends on project requirements, team expertise, and performance needs.

21,674

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Pros of Tornado

  • Lightweight and fast, with excellent performance for handling many concurrent connections
  • Built-in asynchronous networking library, ideal for real-time applications and WebSockets
  • Non-blocking I/O operations, allowing efficient handling of long-polling requests

Cons of Tornado

  • Smaller ecosystem and fewer third-party extensions compared to Django REST Framework
  • Steeper learning curve, especially for developers new to asynchronous programming
  • Less opinionated, requiring more manual configuration and setup for complex applications

Code Comparison

Tornado example:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, World!")

if __name__ == "__main__":
    application = tornado.web.Application([(r"/", MainHandler)])
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Django REST Framework example:

from rest_framework.views import APIView
from rest_framework.response import Response

class HelloWorldView(APIView):
    def get(self, request):
        return Response({"message": "Hello, World!"})

# In urls.py
urlpatterns = [
    path('hello/', HelloWorldView.as_view(), name='hello-world'),
]
14,938

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • Asynchronous: Built on asyncio, allowing for high-performance, non-blocking I/O operations
  • Lightweight: Minimal dependencies and a smaller codebase, making it more suitable for microservices
  • Flexible: Can be used for both client and server-side HTTP, as well as WebSockets

Cons of aiohttp

  • Less opinionated: Requires more boilerplate code for common REST API patterns
  • Smaller ecosystem: Fewer third-party extensions and integrations compared to Django REST Framework
  • Steeper learning curve: Asynchronous programming concepts may be challenging for beginners

Code Comparison

aiohttp server example:

from aiohttp import web

async def hello(request):
    return web.Response(text="Hello, World!")

app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)

Django REST Framework view example:

from rest_framework.views import APIView
from rest_framework.response import Response

class HelloView(APIView):
    def get(self, request):
        return Response("Hello, World!")

Both frameworks offer powerful tools for building web APIs, but they cater to different use cases. aiohttp is ideal for high-performance, asynchronous applications, while Django REST Framework provides a more comprehensive, batteries-included approach for building RESTful APIs within the Django ecosystem.

64,773

Fast, unopinionated, minimalist web framework for node.

Pros of Express

  • Lightweight and minimalist, allowing for more flexibility and customization
  • Faster performance due to its lightweight nature and Node.js runtime
  • Larger ecosystem with more middleware and plugins available

Cons of Express

  • Less opinionated, requiring more setup and configuration for complex projects
  • Lacks built-in features like authentication and ORM, which Django REST Framework provides out-of-the-box
  • Steeper learning curve for beginners due to its flexibility and less structured approach

Code Comparison

Express route handling:

app.get('/api/users', (req, res) => {
  // Handle GET request for users
  res.json(users);
});

Django REST Framework view:

class UserList(APIView):
    def get(self, request):
        # Handle GET request for users
        return Response(users)

Both frameworks offer concise ways to handle API endpoints, but Express uses a more functional approach, while Django REST Framework leverages class-based views. Express provides more flexibility in how routes are defined and handled, while Django REST Framework offers a more structured and opinionated approach with built-in features for common API tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Django REST framework

build-status-image coverage-status-image pypi-version

Awesome web-browsable Web APIs.

Full documentation for the project is available at https://www.django-rest-framework.org/.


Funding

REST framework is a collaboratively funded project. If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.

The initial aim is to provide a single full-time position on REST framework. Every single sign-up makes a significant impact towards making that possible.

Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, Spacinov, Retool, bit.io, PostHog, CryptAPI, FEZTO, Svix, and Zuplo.


Overview

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

Below: Screenshot from the browsable API

Screenshot


Requirements

  • Python 3.8+
  • Django 4.2, 5.0, 5.1

We highly recommend and only officially support the latest patch release of each Python and Django series.

Installation

Install using pip...

pip install djangorestframework

Add 'rest_framework' to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Example

Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups.

Startup up a new project like so...

pip install django
pip install djangorestframework
django-admin startproject example .
./manage.py migrate
./manage.py createsuperuser

Now edit the example/urls.py module in your project:

from django.contrib.auth.models import User
from django.urls import include, path
from rest_framework import routers, serializers, viewsets


# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'is_staff']


# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


# Routers provide a way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

We'd also like to configure a couple of settings for our API.

Add the following to your settings.py module:

INSTALLED_APPS = [
    ...  # Make sure to include the default installed apps here.
    'rest_framework',
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    ]
}

That's it, we're done!

./manage.py runserver

You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the Login control in the top right corner you'll also be able to add, create and delete users from the system.

You can also interact with the API using command line tools such as curl. For example, to list the users endpoint:

$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
[
    {
        "url": "http://127.0.0.1:8000/users/1/",
        "username": "admin",
        "email": "admin@example.com",
        "is_staff": true,
    }
]

Or to create a new user:

$ curl -X POST -d username=new -d email=new@example.com -d is_staff=false -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
{
    "url": "http://127.0.0.1:8000/users/2/",
    "username": "new",
    "email": "new@example.com",
    "is_staff": false,
}

Documentation & Support

Full documentation for the project is available at https://www.django-rest-framework.org/.

For questions and support, use the REST framework discussion group, or #restframework on libera.chat IRC.

Security

Please see the security policy.