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

bash
pip install flask flask-restful

Creating a Simple Flask REST API

python
from flask import Flask, request, jsonify
from flask_restful import Api, Resource
app = 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

bash
pip install django djangorestframewor

Setting Up a Django REST API

  1. Create a Django Project
  • bash
  • django-admin startproject myapi cd myapi
  1. Create an App
  • bash
  • python manage.py startapp api
  1. Define a Model (models.py)
  • python
  • from django.db import models class Item(models.Model): name = models.CharField(max_length=255) description = models.TextField()
  1. Create a Serializer (serializers.py)
  • python
  • from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__'
  1. Create a View (views.py)
  • 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
  1. Define URL Patterns (urls.py)
  • python
  • from django.urls import path from .views import ItemListCreate urlpatterns = [ path('items/', ItemListCreate.as_view(), name='item-list'), 

Run the Server

  • 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

Popular posts from this blog

Best Practices for Secure CI/CD Pipelines

What is DevSecOps? Integrating Security into the DevOps Pipeline

SEO for E-Commerce: How to Rank Your Online Store