Search code examples
djangodjango-modelsdjango-templatesdjango-rest-frameworkdjango-modeladmin

Calling api without knowing ip address in django


I have a post request

http://localhost:8000/api/orders/shipment

what i want to do is i dont want to pass domain/ip address and access the api something like Django admin console give "172.18.0.1 - - [08/Sep/2017 14:30:29] "POST /adminorder/order/import/ HTTP/1.1" 200 "

I searched in the django documentation get_absolute_url() method is there to define custom urls, I am not getting how to use this in this scenario.


Solution

  • I believe it's impossible to use a relative url in requests, but you can get around this by creating a function which prepends the relevant domain to your url. (Make sure to import your settings file!)

    from django.conf import settings
    
    development_url = "http://localhost:8000/"
    production_url = "http://myapisite.com/"
    
    def create_url(relative_url):
        # If you are on your development server. This is assuming your development always has DEBUG = True, and your production is always DEBUG = False
        if settings.DEBUG:
            return development_url + relative_url
    
        # Production
        return production_url + relative_url
    

    Therefore print(create_url("api/test/anothertest")) will return http://localhost:8000/api/test/anothertest.

    And this is how you would use it:

    url = create_url("api/orders/shipment/")
    data = requests.post(url=url, data=content, headers = headers)