How to update myapp/urls.py with the proper URLPATTERN?

my app structure is like this

/dose/
-----/api/
---------/atomicservice1.py
--------/atomicservice2.py
--------/atomicservice3.py

The contents of atomicservice1.py is…

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def hello_world(request):
return Response({“message”: “Hello, world!”})

Just for testing, I will flesh it out as I get it working.

do I need to create another urls.py under /api/ and include from /dose/urls.py?

Do you need to?

No. There’s no requirement that you do it that way.

However, it is the generally-accepted Django practice to keep your urls organized by Django app.

But, it’s certainly valid for you to include a specific url in your root urls.py file.

Ken,

Thanks, so I can add the URLPATTERN to my /dose/urls.py

The question remains what would the URLPATTERN for /dose/api/atomicservice1.py look like since it isn’t inside the views.py?

Assume for the moment that your hello_world view was in views.py.

What would your url definition for it look like?

Ok fair enough.

I tried

path(‘/api/’, views.hello_world.as_view())

I tried moving

@api_view()
def hello_world(request):
return Response({“message”: “Hello, world!”})

to my /dose/views.py

and setting path(‘/api/’, views.hello_world.as_view()),

but got path(‘/api/’, views.hello_world.as_view()),
AttributeError: ‘function’ object has no attribute ‘as_view’

]

Ok Ken,

Progress,

my /dose/urls.py

path(‘api/myhello_world/’, views.myhello_world.as_view()),

my /dose/views.py has

class myhello_world(APIView):
#@api_view()
def hello_world(request):
return Response({“message”: “Hello, world!”})

and

http://localhost:8000/dose/api/myhello_world/

gives me

GET /dose/api/myhello_world/

HTTP 405 Method Not Allowed Allow: OPTIONS Content-Type: application/json Vary: Accept { “detail”: “Method "GET" not allowed.” }
but at least it is getting through, fix the method and get a response. but I would still like to know how to do that with my external one file per service I described

Real progress.

Changed the APIView to

class myhello_world(APIView):
#@api_view()
def get(self, request, format=None):
return Response({“message”: “Hello, world!”})

and got

HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { “message”: “Hello, world!” }

So how do I move this to the one file per service structure I described in my original question?

Ok thanks Ken, with minimal hand holding and hints, I arrived at the solution.

in my /dose/urls.py

from .api.atomicservice1 import service1

from .api.atomicservice2 import service2

from .api.atomicservice3 import service3

in URLPATTERNS

path(‘api/atomicservice1/’, service1.as_view()),
path(‘api/atomicservice2/’, service2.as_view()),
path(‘api/atomicservice3/’, service3.as_view()),

and all is well.

1 Like