DEV Community

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

Posted on

4

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.

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay