---
# System prepended metadata

title: LAMBDAS AND API

---

# LAMBDAS AND API

# **Naming the lambda functions:**

- We will be following **snake case** for naming the lambdas. While naming the lambda, we can use the verbs, i.e. **get, create, update**, etc. The convention would be as follows:


> ✅ **webd_serviceName_functionName**

Ex. **webd_learning_checkPremiumUser.**

This lambda function is for checking if the user is premium or not. Here the name of the service is learning and name of the API is *checkPremiumUser*

- For any event-related lambda/APIs, the convention would be as follows:


> 📢 **webd_event_eventName_functionName**

Ex. **webd_event_christmas_sendGifts.**

This lambda function is for sending gifts to users during some Christmas event hosted by MyWays. Here, since it is an event, it has an event, then eventName as Christmas, and then the API name.

- For the functions that are triggered by other functions or are not solely responsible for generating responses to an API endpoint, the convention would be:


>  📢**webd_trigger_triggeringFunction_functionName**


  For ex. **webd_trigger_register_sendVerificationCode.**

Here, we have a trigger fu

- For the **authorizers,** the convention would be:


> 📢 **webd_authorizer_authorizerFor_functionName**


For ex. **webd_authorizer_user_premiumUser.**

Here, this is the authorizer for user to check if he is premium user or not. This authorizer can be put on the API gateway which consists of API for the premium user.

### How to name the function:

1. Generally, the function does one of the four things:
2. Create a new entity
3. Read an already created entity
4. Update an entity
5. Check for some conditions. For ex: is the user premium or not, has the user seen the popup or not, is the user registered for Bootcamp or not, etc.

While naming the function, we can make sure that the function starts with the verb to make the function name self-descriptive. Convention for verbs are:

- **create,** if a function creates a new entity.

```jsx
const createUser = () => {
	// logic goes here
}

const createBootcampUser = () => {
	// logic goes here
}

const createPracticumUser = () => {
	// logic goes here
}
```

- **get,** if a function reads the data.

```jsx
const getUser = () => {
	// logic
}

const getMessageNotification = () => {
	// logic goes here
}

const getPremiumUsers = () => {
	// logic goes here
}
```

- **update**, if the function updates an already created entity

```jsx
const updateUser = () => {
	// logic goes here
}

const updateBlog = () => {
	// logic goes here
}

const updateProfile = () => {
	// logic goes here
}
```

- **is**, if the function checks for some conditon.

```jsx
const isUserPremium = () => {
	// logic goes here
}

const isBootcampUser = () => {
	// logic goes here
}

// There may be some case where "has" seems to be grammatically correct, 
// for ex: hasUserSeenTheNotification.
// in such cases, we can change it to "isNotificationSeenByTheUser"
const isNotificationSeenByTheUser = () => {
	// logic goes here
}

```

## Practices to follow when writing a Lambda Function:

- **Write your codes in chunks:**  The best way to unit test your code is to write it with unit testing in mind. Try to keep your code in the main handler method to a minimum, only routing and calling other functions. This way you can test the other functions in isolation.
- **Run local:** Serverless framework provides the [capability](https://serverless.com/framework/docs/providers/aws/cli-reference/invoke-local/) to run your function locally without needing to deploy it. Your code lives in your local machine while it emulates the AWS Lambda function environment for you. It is very helpful to have your data sample ready before you start coding.
- **Use [environment variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)** to pass operational parameters to your function**.**

# API GATEWAY

Kebab case for gateways.

# HTTP METHODS:

We mostly use only **FOUR** types of methods: **GET, POST, PATCH, DELETE**. 

## GET:

- These requests should only be used for fetching. No manipulation/creation of data should be done on this request.
- Data from the client should be sent using query parameters.
- The naming convention for query parameters is **snake_case.**
- If the doesn't change frequently, make sure to use Redis.

## POST:

- These requests should be used for creating the data.
- The data should be sent in the body.
- The keys for the JSON data should be in **snake_case.**

## PATCH:

- These request should be used whenever we are updating any exisiting document in the database.
- The data should be in the body

## **DELETE:**

- These request should be used when we are removing/deleting an existing document from the database.


### **NAMING CONVENTION FOR API ENDPOINTS:**

> ✅ **No verbs should be present in the endpoint name and noun should be in the plural form**


> 🚫 **An API endpoint cannot be name /getUser or /updateUser or /createUser**


- For fetching data GET method should be used and API endpoint name should only reference to the model name.


    ✅ **GET /users** : This endpoint will return a list of all the users



- For fetching based on specinc id or any other parameter.


    ✅ **GET /users/:id** : This endpoint should retrun user with the given id


- For creating a new user,


    ✅ **POST /users** : This API should create a new user


- For updating any information of existing user

    ✅ **PATCH /users/:id**     This endpoint should update the info of user with the given id


- For deleting any user


    ✅ **DELETE /users/:id** : This should delete the user with the given id.


### General Practices to follow:

- Always make the UI first and note the exact data which is required. Then while designing the API, **only send the required data to the client**. This reduces the payload.
- Always wrap the QUERYING/CREATING logic in **try-catch** block.
- Use aggregations wherever possible.


> ✅ **Use of **project** and **select** in mongoose for reducing payload and selecting required data.**


### Response type and Error codes:

### Convention for writing error messages:

A good error message should be descriptive. It should mention whatever went wrong, why it went wrong and a key to fix it, if possible.

**For example:**
#### If in the function **updateUser,** the userId passed by the client doesn't exist. So, a lame error message would be:


> ⛔ user_id does not exist.

#### A more descriptive error message can be:

> ✅ **User cannot be updated as a user with the userId 678393930gb2873y538 doesn't exist.**



#### Always provide context with the error message.

> ⛔ invalid format for the image.

> ✅ **Invalid format for Image. txt/jpeg/png is expected but pdf is provided.**


Try to be as descriptive with the error message as possible. This leads to a good time while debugging.

> 📢 **For function which is interacting with AWS, always make sure to log the errors. This makes it easy for the DevOps team to resolve the error.**


### Response Format:

- The response should always be in **JSON format.**
- Structure of the response object should be:

```jsx

{
	// If any message needs to be sent to the client. This can be empty but the key should
	// always be present.
	"message" : ""
	// Each response should be wrapped in "data".
	data: {
		key_name_1 : {},
		key_name_2 : {}/ ...

	}
}

// In case of error:
{
	"message" : error_message
	data: null
}
```

- Status code should be used wisely. We are only using these status codes:
    - **200 Success** : This denotes that everything went well and the response has been successfully delivered to the client.
    - **400 Bad Requests**: This denotes that the client-side input has failed documentation/validation.
    - **401 Unauthorized:** This denotes that the user is unauthorized for accessing a resource. Usually, it returns when a user is not verified.
    - **403 Forbidden:** This denotes that the user is inappropriate and is not allowed to access a resource even after being verified.
    - **404 Not Found:** This denotes that no resources are found.
    - **500 Internal server error:** This is a common server error.

# **DOCUMENTATION OF APIS**

Documentation of each API is a must. API documentation should have:

- endpoint
- method
- description
- headers
- body
- query_parameters
- request_parameter
- response-structure
- example-request
- example-response

```jsx
endpoint: /profile/:id
method: GET
description: returns the profile of the user with given id.
headers: Auth header
body: {}
query_parameters: {}
request_parameters: {"id"}
reponse_structure: {
                    message: "",
                    data:{
                            user_id:
                            name: 
                            roll_no:
                        }

                    }
```

> ✅ **INPUT VALIDATION** i**s done using JOI. Every param, which a lambda receives should be validated against JOI.**

> ✅ **We can use Sentry for logging errors both at the front end and backend(lambdas).**


### Documentation of Lambda Functions:
Lambda would be documented at the function level. This means any function inside the lambda should have its documentation above it.

### Example
```
/**
    name: mainFunction
    description: A function to return full name.
    parameters: firstName: String, lastName: String
    return: fullName: String
*/

function mainFunction(firstName, lastName) {
    const fullName = firstName + " " + lastName
    return fullName
}

```

