REST API
Published: 2024-04-23 15:34:19

1. We should not use only 3000 or 5000 for our port number. We should use user available port number. For that we need , **process** which is a global object then we need **env** its a property of process and then PORT.

`conts port = process.env.PORT || 3000`
`app.listen(port, () => {console.log(`Started listening ${port})`}


##Query String Parameter


2. There are the query which are added to **url **after  question mark(?). 

`http://localhost:5000/api/posts/2024/24?sortBy=name`


##How to read query parameter

3. `res.send(req.query)`


##Handling Get Request 

4. `courses.find(c => c.id === parseInt(req.params.id))`

find is used for finding value of an array. => will return a boolean value which is compared with parseInt. Because req.params.id returns a string value.



##How to response to HTTP Post request

The HTTP response to Post method,

```

    app.use(express.json())
    app.post('/api/courses', (req, res) => {
        const course = {
            id: courses.length + 1,
            name: req.body.name
        }
        courses.push(course)
        res.send(course)
    })

```


##PostMan

we need Post Man desktop for local work


1. req.params.id and req.body.name are both used to access data sent to the server, but they are typically used in different contexts.

req.params.id: This is used to access route parameters in Express. When you define a route with a parameter in Express, such as /users/:id, any value passed in the URL after /users/ will be accessible as req.params.id. Route parameters are typically used for identifying a specific resource in RESTful APIs. For example, in a URL like /users/123, 123 would be accessible as req.params.id.

```

    app.get('/users/:id', (req, res) => {
        const userId = req.params.id;
        // Use the userId to retrieve user data from a database, for 
    example
    });

```

2. req.body.name: This is used to access data sent in the body of a POST or PUT request. When you submit a form or send data in the body of a request, you can access that data using req.body. For example, if you have a form field named name, you can access its value using req.body.name.
javascript

```

    app.post('/submit-form', (req, res) => {
        const name = req.body.name;
        // Use the name submitted in the form
    });

```


---



##Input Validation

In a typical HTTP request-response cycle, you can only send one response back to the client. Once a response is sent using res.send(), res.json(), res.sendFile(), or similar methods, the server cannot send another response for the same request. Any code after sending the response will not be executed in the context of handling that particular request.

For validation we use npm joi,
- `npm i joi`

```
    app.post('/api/courses', (req, res) => {
        //handleing with joi
        const schema = {
            name: Joi.string().min(3).required()
        }
        const result = Joi.ValidationError(req.body, schema)

        if(result.error){
            res.status(400).send(result.error.details[0].message)
            return;
        }
        // ---
        const course = {
            id: courses.length + 1,
            name: req.body.name
        }

        courses.push(course)
        res.send(course)
    })
```

##Put request