0% found this document useful (0 votes)
8 views

Custom Api For Sorsu Dms

Uploaded by

Jeysi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Custom Api For Sorsu Dms

Uploaded by

Jeysi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

To create a custom API for your Django system, you'll follow a series of steps that enable your

application to expose specific data and functionalities through endpoints, which other systems can
interact with. Django makes this easier with Django REST Framework (DRF), which is a powerful toolkit
for building Web APIs. Here's how you can set up your own custom API using Django and Django REST
Framework:

Steps to Create a Custom API in Django:

1. Install Django REST Framework (DRF)

First, you'll need to install Django REST Framework (DRF), which is commonly used for building APIs in
Django.

```bash

pip install djangorestframework

```

2. Update `settings.py`

Add `'rest_framework'` to your `INSTALLED_APPS` in `settings.py`:

```python

INSTALLED_APPS = [

# your other apps

'rest_framework',

```

3. Create a Serializer
A serializer is used to convert complex data types (like Django models) into JSON (or other content
types) and vice versa.

For example, if you have a model called `Product`, create a serializer for it.

```python

from rest_framework import serializers

from .models import Product

class ProductSerializer(serializers.ModelSerializer):

class Meta:

model = Product

fields = '__all__' # Or specify particular fields ['name', 'price', 'description']

```

4. Create Views for Your API

There are multiple ways to create API views using DRF:

- Function-based views (FBV) for simpler APIs.

- Class-based views (CBV) for more flexibility.

Example of a simple function-based view:

```python

from rest_framework.decorators import api_view

from rest_framework.response import Response

from .models import Product


from .serializers import ProductSerializer

@api_view(['GET'])

def product_list(request):

products = Product.objects.all()

serializer = ProductSerializer(products, many=True)

return Response(serializer.data)

```

Example of a class-based view:

```python

from rest_framework import generics

from .models import Product

from .serializers import ProductSerializer

class ProductList(generics.ListCreateAPIView):

queryset = Product.objects.all()

serializer_class = ProductSerializer

```

5. Configure URL Routing

To map your views to URLs, create routes in your `urls.py` file.

Example in `urls.py`:
```python

from django.urls import path

from .views import product_list, ProductList

urlpatterns = [

# For function-based view

path('api/products/', product_list, name='product-list'),

# For class-based view

path('api/products/', ProductList.as_view(), name='product-list'),

```

6. Test Your API

Run your Django server and navigate to the API endpoint (`/api/products/`) in your browser or use a
tool like [Postman](https://www.postman.com/) or `curl` to test your API:

```bash

curl http://127.0.0.1:8000/api/products/

```

This should return a JSON response with a list of all products in your database.

7. Adding POST, PUT, DELETE Requests


If you want your API to support creating, updating, and deleting resources, you can implement those
functionalities in your views.

For example, a class-based view for handling all CRUD operations:

```python

from rest_framework import generics

from .models import Product

from .serializers import ProductSerializer

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):

queryset = Product.objects.all()

serializer_class = ProductSerializer

```

Update your `urls.py` to include the detail view for individual product retrieval, update, or deletion:

```python

urlpatterns = [

path('api/products/', ProductList.as_view(), name='product-list'),

path('api/products/<int:pk>/', ProductDetail.as_view(), name='product-detail'),

```

You can then make GET, PUT, DELETE requests to `/api/products/<id>/` to interact with individual
product records.
8. Authentication and Permissions (Optional)

You may want to restrict access to your API, allowing only authenticated users or certain roles to
access or modify data.

To add authentication and permissions:

```python

from rest_framework.permissions import IsAuthenticated

from rest_framework.authentication import TokenAuthentication

class ProductList(generics.ListCreateAPIView):

queryset = Product.objects.all()

serializer_class = ProductSerializer

authentication_classes = [TokenAuthentication]

permission_classes = [IsAuthenticated]

```

Make sure to also install and set up Django's token authentication if you're using it:

```bash

pip install djangorestframework-simplejwt

```

Update `settings.py`:
```python

REST_FRAMEWORK = {

'DEFAULT_AUTHENTICATION_CLASSES': (

'rest_framework_simplejwt.authentication.JWTAuthentication',

),

```

9. Testing in Postman or Curl

After setting everything up, test the endpoints with Postman or any API client to see how it behaves
with GET, POST, PUT, and DELETE requests.

Example POST request (creating a new product):

```bash

curl -X POST -d "name=New Product&price=29.99" http://127.0.0.1:8000/api/products/

```

---

Key Points:

- Django REST Framework is essential for building custom APIs in Django.

- Use Serializers to convert your Django models into JSON or other formats.

- Function-based views (FBVs) or Class-based views (CBVs) can handle API logic.

- Test your API using Postman or curl to ensure it works correctly.


Would you like to go deeper into any specific part of the API creation process?

You might also like