How to Use RESTful APIs with Django
The REST acronym stands for Representational State Transfer, which is an architectural design.
Usually when we use the term RESTful
API stands for Application Programming Interface, which is a software application that we interact programmatically, instead of using a graphical interface.
RESTful API available the information you store in your databases using a common format, such as XML or JSON.
Example ipstack Location API https://ipstack.com/
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index),
] views.py
#views.py from django.shortcuts import render, redirect import requests # def index(request): # response = requests.get('http://api.ipstack.com/110.54.244.203?access_key=7f851d241fee253a7abbbdd1ca27f73a') # geodata = response.json() # return render(request, 'home.html', { # 'ip': geodata['ip'], # 'country': geodata['country_name'] # }) def index(request): response = requests.get('http://api.ipstack.com/110.54.244.203?access_key=7f851d241fee253a7abbbdd1ca27f73a') geodata = response.json() return render(request, 'home.html', { 'ip': geodata['ip'], 'country': geodata['country_name'], 'latitude': geodata['latitude'], 'longitude': geodata['longitude'], 'api_key': 'AIzaSyB6QBZAvLhPI-e-U8k3rT0MDBn2-w8lqAw', })templates/home.html
//templates/home.html {% extends 'base.html' %} {% block content %} <h2>GEO API</h2> <p>Your ip address is <strong>{{ ip }}</strong>, and you are probably in <strong>{{ country }}</strong> right now.</p> <iframe width="900" height="430" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/view?center={{ latitude }},{{ longitude }}&zoom=8&key={{ api_key }}" allowfullscreen></iframe> {% endblock %}templates/base.html
/templates/base.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/> <title>{% block title %}How to Use RESTful APIs with Django{% endblock %}</title> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <a class="navbar-brand">Cairocoders</a> </div> </nav> <div class="container"> <div class="col-md-12 well"> <h3 class="text-primary">How to Use RESTful APIs with Django</h3> <hr style="border-top:1px dotted #ccc;"/> {% block content %} {% endblock %} </div> </div> </body> </html>