Home > other >  Get data from external URL in JSON format with Django REST
Get data from external URL in JSON format with Django REST

Time:11-22

I want to do simple Rest API in Django. It's my first approach to Rest in django, but for now it isn't going that bad ;)

For now I have a model database with two fields brand and model. With the use of Postman, I can GET, POST and DELETE objects, cool.

But what I'm stuck with is -> When I POST an object, first I'd like to check if that model with given brand even exists. I want to check it on specific website: link. (In the URL of that website I can change brand name so it gives me a list of model with given brand)

My approach would be, when request.method=='POST' first GET data from website, load it to a model and then somehow compare it with data in POST request. But I don't know how to get to that point :)

Is it a good approach or is there a way to directly look at data on the given website?

(For me there is no need to give you my code, because there is nothing special in it, but tell me if I'm wrong!)

CodePudding user response:

Given your information you can handle this with the following approach:

import requests

API_URL = "https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/audi?format=json"
SEARCH_FOR_MODEL = "RS5"

try:
    r = requests.get(API_URL)
    models = r.json()
except:
    logging.WARNING(f"Fetch models from {API_URL} failed")

result = next(
    (model for model in models["Results"] if model["Model_Name"] == SEARCH_FOR_MODEL),
    None,
)

if not result is None:
    print(f"Model {SEARCH_FOR_MODEL} found")
else:
    print(f"Model {SEARCH_FOR_MODEL} not found")

This is based on the link you provide for the API endpoint. They may also offer a filter function for models. Then it is not necessary to search the entire response.

Searching for values in a dictionary from this post: https://stackoverflow.com/a/8653568/4151233

  • Related