Home > database >  Django: Fetching data from an open source API
Django: Fetching data from an open source API

Time:01-19

I am trying to fetch public holiday data for France, Australia and Germany from https://date.nager.at/ with the documentation at https://date.nager.at/swagger/index.html and store it in a JSON file.

Until now, I have created an endpoint /fetch_and_save with its own URL, but only managed to write dummy data in the views.py file. How do I fetch the data above and store it in a database through Django?

Edit: I have been asked to show the code. I ran

python3 manage.py startapp fetch_and_save

to create the fetching application, and I have the following URL patterns in storefront/urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('fetch_and_save/', include('fetch_and_save.urls')),
]

then I added function in fetch_and_save/views.py:

def say_hello(request):
    return HttpResponse('Fetch the data from date.nager.at here')

and I called that in fetch_and_save/urls.py:

urlpatterns = [
    path('', views.say_hello)
]

That's it. It's just a hello world app.

CodePudding user response:

Here you have some clues, how to do that in simple way:

fetch_and_save/views.py

import json
import requests


def get_public_holidays(request, year, tag):
    response = requests.get(f'https://date.nager.at/api/v2/PublicHolidays/{year}/{tag}')
    with open(f'public_holidays_{tag}_{year}.json', 'w') as outfile:
        json.dump(response.text, outfile)
    ...

fetch_and_save/urls.py

urlpatterns = [
    path('<int:year>/<str:tag>/', views.get_public_holidays)
]

Then if you add i.e. /2020/DE you will fetch the public holidays 2020 of Germany and save it to the json file with a name public_holidays_DE_2020.json.

  •  Tags:  
  • Related