DEV Community

Cover image for How to write Simple Endpoint and Functions
Srushti Kulkarni
Srushti Kulkarni

Posted on

How to write Simple Endpoint and Functions

A month ago I’ve joined KarmanX and where I learnt about how to write simple to advanced level of functions and its endpoints. I’ve got an opportunity to attend the Ankita Mam’s Session, where she explained how to write simple and complex functions and how the API call works, so here I’m going to explain in short how to think and write this functions.

Image description

From the above dig. in simple terms we can say that the client is requesting to server, to extract the data from movie database but now think like a developer perspective. Here we know, the client is requesting to server, to get or to extract all movies from database. From this line we can get some idea for how to send request.

Basically app.get(‘/movies’,async(req,res)=>{}) is requesting to server to get this movie data whenver user writes ‘/movies’. Inside the try block I’ve declared result variable where I’m calling a function which extract all the movies. Here we are using try-catch block for error handling.

I’ve declared a function getAllMovies which returns movies. Inside the try block I’ve written if the movies are not present in the movie database [i.e I’m checking the length of the result], it will throw an error 404 with a message ‘No movies found!’. If the movies are present in the datbase, then it will respond with result.

In the catch block if any internal error is there then it will throw an error 500 with a message internal server error. Here I’ve used async-await. The keyword async before a function makes the function return a promise and the await keyword can only be used inside the async function. The await keyword makes the function pause the execution and wait for resolved promise.

Top comments (0)