# How to write API logics

When creating APIs on Blockflow, you define the logic that handles incoming requests, interacts with databases, and generates appropriate responses using TypeScript. Before you start coding, it's essential to understand the following concepts:

1. Context
2. Database Interactions
3. Secrets
4. Available Libraries

## Context

The `context` variable is injected into the API handler function and provides access to the incoming request and the outgoing response.

1. **Request**: The `request` object within the `context` allows you to access query parameters passed when calling the API. For example:

This variable gives your access to query parameters you passed while calling APIs.

```typescript
const user = context.request.query.user;
```

This code retrieves the value of the `user` query parameter from the API request.

2. **Response**: The `response` object within the `context` is used to generate the API response that will be returned to the client. You can assign values to the `response` object and return it at the end of the handler function.&#x20;

For example:

```typescript
export const handler = async (context: any, bind: Function) => {
    let {
        request,
        response
    } = context;
    
    response = { 
        x: "1"
    };

    return response;
};
```

Your API response will look like:-&#x20;

```json
{
    x: '1'
}
```

## Database Interactions

Blockflow provides a seamless way to interact with your managed databases within your API logic. To learn how to read from and write to your databases, refer to this guide.

{% content-ref url="/pages/EF48HJGMwYz8GNGSYLG6" %}
[Working with Managed Database](/guides/creating-a-database/working-with-managed-database.md)
{% endcontent-ref %}

## Secrets

Secrets allow you to securely store and access sensitive information, such as API keys or private keys, without hardcoding them in your API logic. You can access secrets using the `secret` variable.&#x20;

For example:

```typescript
// accessing a secret
const wallet = new ethers.Wallet(secret.Private_Key);
```

To manage your secrets, use Blockflow's Secret Manager. Refer to this guide for more information.

{% content-ref url="/pages/GgExXh3QJzesy7wGhA86" %}
[Secret Manager](/overview/secret-manager.md)
{% endcontent-ref %}

## Libraries

Blockflow provides several pre-imported libraries that you can use in your API logic:

1. **Ethers.js**: A popular Ethereum library for interacting with the Ethereum blockchain and smart contracts.

You can check out the library [here](https://www.npmjs.com/package/ethers).

Example usage:

```typescript
const wallet = new ethers.Wallet(secret.Private_Key);
```

2. **BigNumber.js**: A library for handling large numbers and performing arithmetic operations.&#x20;

You can check out the library [here](https://www.npmjs.com/package/bignumber.js/v/4.0.4).

Example usage:

<pre class="language-typescript"><code class="lang-typescript"><strong>let userAmount = new BigNumber(amount);
</strong></code></pre>

3. **PushUtils**: A utility library provided by Blockflow for interacting with the Push API.

You can check out the library [here](https://www.npmjs.com/package/@pushprotocol/restapi).

Example usage:

```typescript
const user = await PushUtils.PushAPI.initialize(
    wallet, 
    {
        env: PushUtils.CONSTANTS.ENV.PROD
    }
);
```

### Writing Your API Logic

Now that you understand the key concepts, you can start writing your API logic. Here's a basic template to get you started:

```typescript
import { IContext } from "@blockflow-api/utils";

export const handler = async (context: IContext, bind: Function) => {
  const { request, response } = context;

  // Access request parameters
  const userId = request.query.userId;

  // Interact with databases
  const userDB = bind("Users");
  const user = await userDB.findOne({ id: userId });

  // Generate the response
  response = {
    user: user,
  };

  return response;
};
```

In the `handler` function, you can access the `request` and `response` objects from the `context`, interact with databases using the `bind` function, and generate the appropriate response.

Remember to handle errors appropriately and return meaningful responses to the client.

### Conclusion

Writing API logic on Blockflow using TypeScript provides a powerful and flexible way to define the behavior of your APIs. By leveraging the `context` object, database interactions, secrets, and available libraries, you can create robust and efficient APIs that meet your application's requirements.

If you have any further questions or need assistance with writing API logic on Blockflow, please reach out to our support team via [Discord](https://discord.com/invite/Sa2MjMNkm3).

Happy building with Blockflow APIs!


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.blockflow.network/guides/creating-an-api/how-to-write-api-logics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
