Trying to work with POST request using Postman, cosmosDB and NodeJs

Viewed 67

I am trying to learn the way API's work. Here I am trying to get the POST method to work. I am using this code to make the document in the database,

app.post('/add', async (req, res) => {
    try {

        const data = require('./test.json');
        

    const newItemId = Math.floor(Math.random() * 1000 + 10).toString();
    
    data.id = newItemId;
    data.Partnership_Id = newItemId;
 
    
    //for testing purpose only
    let documentDefinition = {
    "id": newItemId,
    "name": "Angus MacGyver",
    "state": "Building stuff"
    };
        
    // Open a reference to the database
    const dbResponse = await cosmosClient.databases.createIfNotExists({
        id: databaseId
    });
    let database = dbResponse.database;

    const { container } = await database.containers.createIfNotExists({id: containerId});

    // Add a new item to the container
    console.log("** Create item **");
    const createResponse = await container.items.create(data);
    res.redirect('/');

    } catch (error) {
        console.log(error);
        res.status(500).send("Error with database query: " + error.body);
    }
})

Here I am using test.json for the data input. I am making a fake id using newItemId for data.id and data.Partnership_Id. With this approach, I can make a document in the database and can check on Postman too but there is nothing in the Body tag in Postman. I am confused on this part, I feel like the data for the new document should be passed through the Postman Body rather than me using newItemId for it. This might be a silly question to ask but I am trying to get my head around how API works and how to pass data in them.

1 Answers

IDs are almost always auto generated on the backend (or at least should be) when creating a database resource, so what you have seems to be correct. I would recommend using a library like nanoid to generate the ids though, just to remove the potential for errors.

Its is RESTful convention to return created data, so in this case you would return a JSON on the created document, and then redirect etc on the front end (to ensure complete separation of backend front end - so you can say host them separately). Your approach is also fine and works though.

My advice is to think of your backend and frontend as been completely separate, I would have a project for each personally. This was it is more clear how everything links together.

Related