Use Express to Create Data Dynamically

Ryan Chenkie
InstructorRyan Chenkie
Share this video with your friends

Social Share Links

Send Tweet

Prisma is API-agnostic meaning that it doesn't matter how we build our APIs. They can be REST APIs, GraphQL APIs, or anything else. In this lesson, we see how to use express to accept JSON data to be forwarded off to Prisma to create new records in the database.

Kristian Freeman: [0:00] Real-world applications will need to take this data dynamically from the calls to the endpoint. Prisma doesn't care about how you construct your APIs, whether they be REST APIs, GraphQL APIs, or something else.

[0:13] In this example, since we're using JSON endpoints with Express, we can take this data off of the request body. With Express, if we try to get the request body right away off of the request object, it's going to be undefined.

[0:29] What we have to do is apply a middleware to tell our Express app that it should forward the JSON data that comes in on a request to the handler. To do that, opt into the middleware by calling app.use(express.json()).

[0:43] With that middleware in place, the request body will now be defined. Remove the hard-coded data. Put in the data that comes from the request body. Name will come from body.name, description from body.description, and the price from body.price.

[1:03] Save the endpoint and go back to the REST client that you're using. In the JSON body section, supply some JSON data to send to the endpoint -- name, description, and price. Send the request to add the item to the database. Confirm that it went through in Prisma Studio.