Tuesday, October 8, 2024

Full Documentation: Differences Between REST API and Fast API

 Follow me

FAST API vs Rest API

Full Documentation: Differences Between REST API Using Django and FastAPI

1. Overview of Django and FastAPI

Django

  • Type: Full-stack web framework.
  • Primary Use: Suitable for building robust web applications with a rich set of features.
  • Key Features:
    • Built-in ORM (Object-Relational Mapping).
    • Admin interface.
    • Middleware support.
    • Strong community and ecosystem.
  • Learning Curve: Moderate; useful for those familiar with traditional MVC patterns.

FastAPI

  • Type: Modern, fast (high-performance) web framework for building APIs.
  • Primary Use: Ideal for building APIs quickly with a focus on performance.
  • Key Features:
    • Automatic generation of OpenAPI documentation.
    • Full support for asynchronous programming (async/await).
    • Type hints for data validation.
    • Very lightweight and minimalistic.
  • Learning Curve: Moderate; takes advantage of Python’s type hints for validation and serialization.

2. Key Differences

Feature

Django

FastAPI

Framework Type

Full-stack framework

Lightweight API framework

Performance

Good, but slower due to synchronous nature

Excellent; designed for async operations

Automatic Docs

Requires setup (e.g., drf-yasg)

Automatic generation of OpenAPI docs

ORM

Built-in ORM for database interactions

No built-in ORM; works well with SQLAlchemy

Asynchronous Support

Limited (as of Django 3.1+)

Full support for async/await

Serialization

Uses serializers with Django REST Framework

Uses Pydantic for data validation and serialization

Admin Interface

Built-in admin interface

No built-in admin; needs custom implementation

3. Example: Simple Item API

Example Using Django

Setup Steps:

  1. Install Django and Django REST Framework:

Bash

 

pip install django djangorestframework

  1. Create a Django Project and App:

Bash

 

django-admin startproject myproject

cd myproject

django-admin startapp myapp

  1. Configure settings.py:

Python

 

# myproject/settings.py

INSTALLED_APPS = [

    ...

    'rest_framework',

    'myapp',

]

  1. Define the Model:

Python

 

# myapp/models.py

from django.db import models

 

class Item(models.Model):

    name = models.CharField(max_length=100)

    description = models.TextField()

  1. Create a Serializer:

Python

 

# myapp/serializers.py

from rest_framework import serializers

from .models import Item

 

class ItemSerializer(serializers.ModelSerializer):

    class Meta:

        model = Item

        fields = '__all__'

  1. Create Views:

Python

 

# myapp/views.py

from rest_framework import viewsets

from .models import Item

from .serializers import ItemSerializer

 

class ItemViewSet(viewsets.ModelViewSet):

    queryset = Item.objects.all()

    serializer_class = ItemSerializer

  1. Configure URLs:

Python

 

# myapp/urls.py

from django.urls import path, include

from rest_framework.routers import DefaultRouter

from .views import ItemViewSet

 

router = DefaultRouter()

router.register(r'items', ItemViewSet)

 

urlpatterns = [

    path('', include(router.urls)),

]

  1. Include App URLs in Project URLs:

Python

 

# myproject/urls.py

from django.contrib import admin

from django.urls import path, include

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('api/', include('myapp.urls')),

]

  1. Run Migrations and Start Server:

Bash

 

python manage.py makemigrations

python manage.py migrate

python manage.py runserver

Accessing the API:

  • Create an Item:

http

 

POST /api/items/

Content-Type: application/json

 

{

    "name": "Item 1",

    "description": "This is item 1"

}

  • Get All Items:

http

 

GET /api/items/

 

 

Example Using FastAPI

Setup Steps:

  1. Install FastAPI and Uvicorn:

Bash

 

pip install fastapi uvicorn

  1. Create a Simple API:

Python

 

# main.py

from fastapi import FastAPI, HTTPException

from pydantic import BaseModel

from typing import List

 

app = FastAPI()

 

class Item(BaseModel):

    id: int

    name: str

    description: str

 

items = []

 

@app.post("/items/", response_model=Item)

def create_item(item: Item):

    items.append(item)

    return item

 

@app.get("/items/", response_model=List[Item])

def read_items():

    return items

 

@app.get("/items/{item_id}", response_model=Item)

def read_item(item_id: int):

    for item in items:

        if item.id == item_id:

            return item

    raise HTTPException(status_code=404, detail="Item not found")

 

@app.delete("/items/{item_id}")

def delete_item(item_id: int):

    global items

    items = [item for item in items if item.id != item_id]

    return {"message": "Item deleted"}

  1. Run the Server:

Bash

 

uvicorn main:app –reload

Accessing the API:

  • Create an Item:

http

 

POST /items/

Content-Type: application/json

 

{

    "id": 1,

    "name": "Item 1",

    "description": "This is item 1"

}

  • Get All Items:

http

 

GET /items/

  • Swagger UI for Documentation: Access at http://127.0.0.1:8000/docs for interactive API documentation.

4. Conclusion

Both Django and FastAPI have their strengths and weaknesses:

  • Django is ideal for building full-fledged applications where you need an ORM, admin panel, and built-in features. It's particularly useful for larger projects or those that require more than just an API.
  • FastAPI excels in scenarios where performance is critical, and you need to build APIs quickly. It supports asynchronous programming, making it suitable for high-concurrency applications.

No comments:

Post a Comment

Recursion in DSA using Python

Follow me If you want to understand with  Graphical Representation   click on it. You can find the explanatory video at the bottom of this p...