Building RESTful APIs with Python and Flask/Django

RESTful APIs (Representational State Transfer) allow applications to communicate over HTTP, making them essential for modern web and mobile applications.
Python provides two popular frameworks for building REST APIs: Flask (lightweight and flexible) and Django REST Framework (DRF) (powerful and feature-rich).
1. Building a REST API with Flask
Installing Flask and Flask-RESTful
bashpip install flask flask-restfulCreating a Simple Flask REST API
pythonfrom flask import Flask, request, jsonify
from flask_restful import Api, Resourceapp = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {"message": "Hello, World!"}
api.add_resource(HelloWorld, "/")
if __name__ == "__main__":
app.run(debug=True)
Flask Key Features for REST APIs
- Minimal setup with flexible architecture.
- Supports JSON responses out-of-the-box.
- Works well with SQLAlchemy for database integration.
2. Building a REST API with Django REST Framework (DRF)
Installing Django and DRF
bashpip install django djangorestframeworSetting Up a Django REST API
- Create a Django Project
- bash
django-admin startproject myapi cd myapi
- Create an App
- bash
python manage.py startapp api
- python
from django.db import models class Item(models.Model): name = models.CharField(max_length=255) description = models.TextField()
- python
from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__'
- python
from rest_framework import generics from .models import Item from .serializers import ItemSerializer class ItemListCreate(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer
- python
from django.urls import path from .views import ItemListCreate urlpatterns = [ path('items/', ItemListCreate.as_view(), name='item-list'),
- bash
python manage.py runserver
Django REST Framework Key Features
- Built-in authentication and permissions.
- Powerful serialization and deserialization.
- Browsable API for quick testing.
Choosing Between Flask and Django REST Framework

WEBSITE: https://www.ficusoft.in/python-training-in-chennai/
Comments
Post a Comment