Custom Api For Sorsu Dms
Custom Api For Sorsu Dms
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:
First, you'll need to install Django REST Framework (DRF), which is commonly used for building APIs in
Django.
```bash
```
2. Update `settings.py`
```python
INSTALLED_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
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
```
```python
@api_view(['GET'])
def product_list(request):
products = Product.objects.all()
return Response(serializer.data)
```
```python
class ProductList(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
```
Example in `urls.py`:
```python
urlpatterns = [
```
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.
```python
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 = [
```
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.
```python
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
```
Update `settings.py`:
```python
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
```
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.
```bash
```
---
Key Points:
- 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.