Micah Pearce
Micah Pearce

Reputation: 1945

How to make a different Django Api Url path

Django 2.1, python 3.6, djangorestframework.

When I go to the following url, I can see my data (great!) http://127.0.0.1:8000/api/cards/1 This is what I see on the api page -

HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": "1",
        "card_title": "Hello"
    },
]

I want to be able to go to this url to get to the same data - http://127.0.0.1:8000/api/cards/title/Hello

How can I update my views and urls to do that?

base url

urlpatterns = [
    ...
    path('api/cards/', include('cards.api.urls')),
]

cards.api.urls.py

urlpatterns = [
    path('', CardListView.as_view()),
    path('<str:pk>/', CardDetailView.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

cards.api.views.py

class CardList(generics.ListCreateAPIView):
    permission_classes = ()

    queryset = Card.objects.all()
    serializer_class = CardSerializer


class CardDetail(generics.RetrieveUpdateDestroyAPIView):
    #permisssion_classes = (UserPermission,) # set the permission class
    permission_classes = ()

    queryset = Card.objects.all()
    serializer_class = CardSerializer

I tried adding this to the cards.api.urls.py path('api/cards/title/<str:pk>/', CardDetail.as_view()), , but it still is looking at the id variable instead of the card_title variable.

Upvotes: 1

Views: 5792

Answers (2)

JPG
JPG

Reputation: 88619

I think this would help you,

# base urls.py
urlpatterns = [
    ...
    path('api/', include('cards.api.urls')), # remove "cards/" from url
]

and create a new view class, CardTitleDetail as below and add lookup_field attribute

class CardTitleDetail(generics.RetrieveUpdateDestroyAPIView):
    lookup_field = 'card_title'
    permission_classes = ()
    queryset = Card.objects.all()
    serializer_class = CardSerializer
# cards.api.urls.py
urlpatterns = [
    path('cards/', CardListView.as_view()),  # add "cards/" to the url
    path('cards/<str:pk>/', CardDetailView.as_view()),  # add "cards/" to the url
    path('cards/title/<str:card_title>/', CardTitleDetail.as_view()),  # this is the new url
]

urlpatterns = format_suffix_patterns(urlpatterns)

NOTE
The card_title attribute should be unique across the DB, else it will raise exception!!

Upvotes: 2

Ramanpreet Singh
Ramanpreet Singh

Reputation: 37

you can add another url in your cards.api.urls.py file redirecting to the same api for the same response.

Add this to your urls.py file urlpatterns.

path('title/<str:pk>/', CardDetailView.as_view()),

Then try hitting this http://127.0.0.1:8000/api/cards/title/1

Upvotes: 0

Related Questions