Correct ways of structuring JSON and routing to API resources

64 Views Asked by At

In this link, I have created a JSON structure in a JSON Server API deployed on Replit for a diet managing app I'm developing in JavaScript. For those of you that don't know, JSON Server is an NPM module that allows for the generation and managing of fake REST APIs, used for learning and prototyping. Here are some case examples:

Successful attempt at accessing a specific user in the API through the user's id key:

access_specific_user

Unsuccessfull attempt at accessing a specific meal of a specific user in the API through the user's and meal's id keys:

access_specific_meal_of_specific_user

As you can see, I'm trying to access a specific meal of a specific user, and in the project's code I'm trying to achieve that with the following JavaScript fetch request:

async function fetchMeal(id) {
    try {
        const response = await fetch(`https://dietapp-server.matheusrocha-mu.repl.co/users/${id}/meals/1`);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching meals JSON:', error);
    }
}

It's probably obvious to most of you (it wasn't for me) that this API request won't find anything, since the meals key is a sibling of the user's id key and not its child, and therefore cannot be accessed with an "/" character as I'm intending with the users/${id}/meals/1 route. I tried to figure out a way to solve this by consulting the API routing guide in the JSON Server guide page but I believe my problem lies in a deep lack of mastery either in JSON structuring or in the fundaments of accessing nested resources in an API. I'm relatively new to REST API concepts and to coding in general, so I'm sorry if my question doesn't contain all necessary information for you guys to help me - if so, please tell me what's missing in the comments!

0

There are 0 best solutions below