Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – How do you create a GET endpoint with params?

I am using express and trying to create an API endpoint to accept a GET request like GET /dogs?breed=GOLDEN&name=rex.

What is the best approach to pass parameters into a url? While testing, I created two endpoints as shown below. Neither return a success

router.get('/dogs?breed=GOLDEN&name=rex', breedAndNameController.fetch);

router.get('/dogs?breed=:breed&name=:name', breedAndNameController.fetch);

export const fetch = async (req: any, res: any) => {
    try {
        console.log("success")
        return res.status(200).send("success");
    } catch (err) {
        console.log(err)
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like you’re using express.js (just a guess).

Query-params are not a part of your route.

You have two options now:

Use query strings

Using query-string arguments your url looks like this:

router.get('/dogs', breedAndNameController.fetch);

And your route:

 export const fetch = async (req: any, res: any) => {
        try {

  console.log(req. query);
            return res.status(200).send("success");
        } catch (err) {
            console.log(err)
        }
    }

The call looks like /dogs?breed=asdf&name=test

Use params

Using params your url looks like this:

router.get('/dogs/:breed/:name', breedAndNameController.fetch);

which gives you access like this:

export const fetch = async (req: any, res: any) => {
    try {

        console.log(req.params)
        return res.status(200).send("success");
    } catch (err) {
        console.log(err)
    }
}

And your url looks like /dogs/tset/asdf.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading