Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the Django Rest Framework's default url to a custom

Question says it almost all.

E.g. changing default url (http://127.0.0.1:8000) to a custom (https://api.example.com/v1)

I'm using HyperlinkedModels and everything seems to work properly in development. Moving the app to another server with custom url is giving me problems.

How do I change the default url:

default url 127.0.0.1:8000

To a custom one, let's say:

https://api.example.org/v1/

like image 423
mimoralea Avatar asked Dec 11 '15 19:12

mimoralea


1 Answers

You are mixing two questions in one:

  1. How to run django-rest-framework project on a different domain
  2. How to change URL path of API

To answer the first one I'd say, "Just do it". Django's reverse uses request's domain to build absolute URL.

UPDATE: don't forget to pass Host header from nginx/apache. Below is a sample nginx config:

server {

    location / {
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_pass              http://127.0.0.1:8000;
    }

}

The second (path, mount point) is set in the urls.py:

from django.conf.urls import url, include
from django.contrib import admin

from rest_framework import routers

from quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^v1/', include(router.urls)), # <-------------- HERE
]

enter image description here

like image 187
twil Avatar answered Oct 19 '22 03:10

twil