1

I am going to make an api in django which currently only return hello world when the url is hit. I am new to python and django and find a bit difficult to work in django because of working in PHP and its frameworks for a long time.

I have followed the tutorials but that takes me making the models, templates. but my requirement is simple. How can i achieve this. That when i hit the url of DJango app it return me the hello world or any json object in future.

2
  • 1
    You don't need to have a model, but you are going to need views in order to respond to requests. Commented Oct 11, 2018 at 9:43
  • so i just need a url route to that function in view? and then in that function return \hello world?? Commented Oct 11, 2018 at 9:48

1 Answer 1

3

You define a view, that returns a HTTP response:

# app/views.py

from django.http import HttpResponse

def some_view(request):
    return HttpResponse('hello world')

and then you register your view in the urls.py:

# app/urls.py

from django.urls import url
from app.views import some_view

urlpatterns = [
    url('^my_url/$', some_view),
]

(given this is the root urls.py or there is at least some path to these URL patterns.

Then you can run the server, and access this page with localhost:8000/my_url/ (or another URL given you configured it differently).

You can produce a JSON blob with:

# app/views.py

from django.http import JsonResponse

def some_view(request):
    return JsonResponse({'world': 'earth', 'status': 'hello'})
Sign up to request clarification or add additional context in comments.

12 Comments

just let me test this and understand this will get back to you! actually very new to the django stuff :D
i have tested this and it works like a charm! i have only one question that i have to pass the parameters to the url like for now http://127.0.0.1:8000/my_url/ is working fine but in future i have to make http://127.0.0.1:8000/my_url/name='any name' and i want to controll it in the view
@fatpotato: you can define a URL with named groups (docs.djangoproject.com/en/1.11/topics/http/urls/#named-groups) to capture a value. But the above is rather "un-Django", a typical URL is localhost:8000/my_url/any_name. Or if it is a GET parameter, then you can use request.GET (then the URL is like localhost:8000/my_url?name=any+name.
actually i tried to use http://127.0.0.1:8000/my_url/fatpotato but it is giving me the 404 error.
@fatpotato: not for a POST request, since the data of a POST is added to the HTTP request header. This is not specific to Django, this is how the HTTP protocol works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.