Skip to main content

3 posts tagged with "restapi"

View All Tags

· 7 min read

Overview :

Before two weeks Ryan Dahl (Founder of Node.JS) announced the first version of [Deno](https://deno.land/). As the tagline says A secure runtime for JavaScript and TypeScript. Deno is a runtime for Javascript and Typescript that is based on the V8 JavaScript engine and the Rust programming language. I have been a Node developer for 2 years in the past, if you want to get started with Deno knowing Node.js would be an added advantage. Even though Deno has arrived as a competitor for NodeJS in the industry not so quick but people are sure that it'll take over.

I was reading lot of documentations and materials to understand the difference. So, here are the advantages that i see from Deno,

  • It is Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Deno does not use npm
  • Deno does not use package.json in its module resolution algorithm.
  • All async actions in Deno return a promise. Thus Deno provides different APIs than Node.
  • Uses "ES Modules" and does not support require().
  • Deno has a built-in test runner that you can use for testing JavaScript or TypeScript code.
  • Deno always dies on uncaught errors.

I was very excited as other developers when Deno was announced. In this post i will demonstrate how to create a simple Web API with Deno and deploy to production on Web App with Azure.

PreRequisities:

You will need to have an Azure Subscription. If you do not have an Azure subscription you can simply create one with free trial.

Install Deno :

Using Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

Using Homebrew (macOS):

brew install deno

Using Chocolatey (Windows):

choco install deno

Using Scoop (Windows):

scoop install deno

Services used:

  • Azure Web App
  • Github Actions

Step 1 : Create Deno Rest API

I will not be going through each step on how to create the REST API, however if you are familiar with creating APIs with Node , it is the same way that you need to do. You need to have the main file server.ts which will have those routes defined. (server.ts)

import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
const PORT = 8001;

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Server at ${PORT}`);
await app.listen({ port: PORT });

One feature that i personally liked in DENO is that it provides developers to code with  TypeScript that addresses "design mistakes" in Node.js. In this case i am going to create an API to fetch/add/delete products and my interface would look like as below (types.ts),

export interface Product {
id: String;
name: String;
description: String;
price: Number;
status: String;
}

Similar to how you would define routes in Node, you need to define the routes for different endpoints when user want to execute fetch/add/delete operations as follows(routes.ts),

import { Router } from "https://deno.land/x/oak/mod.ts";
import { delete_product, add_product, get_product, get_products } from "./Controllers/Products.ts";

const router = new Router();

router.get("/", ctx => {
ctx.response.body = "Welcome to Deno!";
});

router.get("/get/:id", get_product);
router.post("/add", add_product);
router.get("/get_all_products", get_products);
router.get("/delete/:id", delete_product);

export default router;

The final step is to create the code for the logic of those each routes. You need to implement the methods which are defined in those routes. For example get_products would look like


import { Product } from "../Types.ts";

let products: Product[] = [
{
id: "1",
name: "Iphone XI",
description: "256GB",
price: 799,
status: "Active"
}
];

const get_products = ({response}: {response: any}) => {
response.status = 200;
response.body = products;
};

You can access the whole code from this Repository.

Run the DENO app:

Once you are good with everything, you can run the app in local and check if the endpoints are working as expected.

deno run -A server.ts

And you would see the app running in port 8001 , and you can access the endpoints as follows ,

Deno API

Step 2 : Create Azure Resources

Now we are good with the first step and you can see the app running successfully in local. As the next step let's go ahead and deploy the app to Azure. Inorder to deploy the app, you need to create a Resource Group first.

Create a ResourceGroup Named Deno-Demo

You can navigate to Azure Portal and search for Resource Group in the search bar and create a new one as defined here!

Next step is to create the Web App , as we are going to deploy this app to a Linux environment, you can set the configuration as follows,

Web App Configuration

Step 3 : Deploy to Azure with Github Actions

One of the recent inventions by Github team that was loved by all developers were Github Actions. Personally i am a big fan of Github actions and i have published few posts earlier explaining the same. To configure the Github Action to our application, first you need to push the code to your github repository.

Create a deno.yml

To deploy the app , we first need to create the workflow under the actions. you can create a new workflow by navigating to Actions tab and create new workflow

New Workflow

I am assuming that you are familiar with important terms of Github Actions, if you are new you can explore here. In this particular example i will be using one package created by Anthony Chu who is a Program Manager in Azure functions team. And my deno.yml looks like below,

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:

build-and-deploy:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v2

- uses: azure/[email protected]
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}

- name: Set up Deno
uses: denolib/setup-deno@master
with:
deno-version: 1.0.2

- name: Bundle and zip Deno app
run: |
deno bundle server.ts server.bundle.js
zip app.zip server.bundle.js
- name: Deploy to Azure Web Apps
uses: anthonychu/azure-webapps-deno-deploy@master
with:
app-name: denodemo
resource-group: deno-demo
package: app.zip
script-file: server.bundle.js
deno-version: "1.0.2"

One important thing you need to verify is the resource-group and the app-name as you created on Azure.

Also you need to add secrets of your application under secrets in Github repository. You can generate a new Service Principal and obtain the secret as below,


az ad sp create-for-rbac --name "deno-demo" --role contributor --scopes /subscriptions/{SubscriptionID}/resourceGroups/deno-demo --sdk-auth

It will generate a JSON like below,

Generate Service Principal

You can copy and paste the JSON under the secret named "AZURE_CREDENTIALS" ,

Add Secret

Now we are good with everything, you can update some file on the repository and see the workflow getting triggered. You can monitor the deployment by navigating to the workflow.

Workflow Execution

Once everything is successful you can navigate to Azure portal and open the Web App endpoint to see if the app is running successfully.

WebApp with Deno API

You can see the app running successfully on Azure.

Deno Web API on azure.

Final words

I really enjoyed learning about the Deno project and created this simple app. I hope this article can be of value for anyone getting started with Deno with Azure.  I see it Deno gaining in popularity, yes. However, I do not see it replacing NodeJS and npm based on several factors. If you found this article useful, or if you have any questions please reach out me on Twitter. Cheers!

· 7 min read

Overview :

Before two weeks Ryan Dahl (Founder of Node.JS) announced the first version of [Deno](https://deno.land/). As the tagline says A secure runtime for JavaScript and TypeScript. Deno is a runtime for Javascript and Typescript that is based on the V8 JavaScript engine and the Rust programming language. I have been a Node developer for 2 years in the past, if you want to get started with Deno knowing Node.js would be an added advantage. Even though Deno has arrived as a competitor for NodeJS in the industry not so quick but people are sure that it'll take over.

I was reading lot of documentations and materials to understand the difference. So, here are the advantages that i see from Deno,

  • It is Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Deno does not use npm
  • Deno does not use package.json in its module resolution algorithm.
  • All async actions in Deno return a promise. Thus Deno provides different APIs than Node.
  • Uses "ES Modules" and does not support require().
  • Deno has a built-in test runner that you can use for testing JavaScript or TypeScript code.
  • Deno always dies on uncaught errors.

I was very excited as other developers when Deno was announced. In this post i will demonstrate how to create a simple Web API with Deno and deploy to production on Web App with Azure.

PreRequisities:

You will need to have an Azure Subscription. If you do not have an Azure subscription you can simply create one with free trial.

Install Deno :

Using Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

Using Homebrew (macOS):

brew install deno

Using Chocolatey (Windows):

choco install deno

Using Scoop (Windows):

scoop install deno

Services used:

  • Azure Web App
  • Github Actions

Step 1 : Create Deno Rest API

I will not be going through each step on how to create the REST API, however if you are familiar with creating APIs with Node , it is the same way that you need to do. You need to have the main file server.ts which will have those routes defined. (server.ts)

import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
const PORT = 8001;

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Server at ${PORT}`);
await app.listen({ port: PORT });

One feature that i personally liked in DENO is that it provides developers to code with  TypeScript that addresses "design mistakes" in Node.js. In this case i am going to create an API to fetch/add/delete products and my interface would look like as below (types.ts),

export interface Product {
id: String;
name: String;
description: String;
price: Number;
status: String;
}

Similar to how you would define routes in Node, you need to define the routes for different endpoints when user want to execute fetch/add/delete operations as follows(routes.ts),

import { Router } from "https://deno.land/x/oak/mod.ts";
import { delete_product, add_product, get_product, get_products } from "./Controllers/Products.ts";

const router = new Router();

router.get("/", ctx => {
ctx.response.body = "Welcome to Deno!";
});

router.get("/get/:id", get_product);
router.post("/add", add_product);
router.get("/get_all_products", get_products);
router.get("/delete/:id", delete_product);

export default router;

The final step is to create the code for the logic of those each routes. You need to implement the methods which are defined in those routes. For example get_products would look like


import { Product } from "../Types.ts";

let products: Product[] = [
{
id: "1",
name: "Iphone XI",
description: "256GB",
price: 799,
status: "Active"
}
];

const get_products = ({response}: {response: any}) => {
response.status = 200;
response.body = products;
};

You can access the whole code from this Repository.

Run the DENO app:

Once you are good with everything, you can run the app in local and check if the endpoints are working as expected.

deno run -A server.ts

And you would see the app running in port 8001 , and you can access the endpoints as follows ,

Deno API

Step 2 : Create Azure Resources

Now we are good with the first step and you can see the app running successfully in local. As the next step let's go ahead and deploy the app to Azure. Inorder to deploy the app, you need to create a Resource Group first.

Create a ResourceGroup Named Deno-Demo

You can navigate to Azure Portal and search for Resource Group in the search bar and create a new one as defined here!

Next step is to create the Web App , as we are going to deploy this app to a Linux environment, you can set the configuration as follows,

Web App Configuration

Step 3 : Deploy to Azure with Github Actions

One of the recent inventions by Github team that was loved by all developers were Github Actions. Personally i am a big fan of Github actions and i have published few posts earlier explaining the same. To configure the Github Action to our application, first you need to push the code to your github repository.

Create a deno.yml

To deploy the app , we first need to create the workflow under the actions. you can create a new workflow by navigating to Actions tab and create new workflow

New Workflow

I am assuming that you are familiar with important terms of Github Actions, if you are new you can explore here. In this particular example i will be using one package created by Anthony Chu who is a Program Manager in Azure functions team. And my deno.yml looks like below,

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:

build-and-deploy:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v2

- uses: azure/[email protected]
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}

- name: Set up Deno
uses: denolib/setup-deno@master
with:
deno-version: 1.0.2

- name: Bundle and zip Deno app
run: |
deno bundle server.ts server.bundle.js
zip app.zip server.bundle.js
- name: Deploy to Azure Web Apps
uses: anthonychu/azure-webapps-deno-deploy@master
with:
app-name: denodemo
resource-group: deno-demo
package: app.zip
script-file: server.bundle.js
deno-version: "1.0.2"

One important thing you need to verify is the resource-group and the app-name as you created on Azure.

Also you need to add secrets of your application under secrets in Github repository. You can generate a new Service Principal and obtain the secret as below,


az ad sp create-for-rbac --name "deno-demo" --role contributor --scopes /subscriptions/{SubscriptionID}/resourceGroups/deno-demo --sdk-auth

It will generate a JSON like below,

Generate Service Principal

You can copy and paste the JSON under the secret named "AZURE_CREDENTIALS" ,

Add Secret

Now we are good with everything, you can update some file on the repository and see the workflow getting triggered. You can monitor the deployment by navigating to the workflow.

Workflow Execution

Once everything is successful you can navigate to Azure portal and open the Web App endpoint to see if the app is running successfully.

WebApp with Deno API

You can see the app running successfully on Azure.

Deno Web API on azure.

Final words

I really enjoyed learning about the Deno project and created this simple app. I hope this article can be of value for anyone getting started with Deno with Azure.  I see it Deno gaining in popularity, yes. However, I do not see it replacing NodeJS and npm based on several factors. If you found this article useful, or if you have any questions please reach out me on Twitter. Cheers!

· 6 min read

I have been working with Cosmos DB for almost 2 years and most of the time i have used SDKs to connect to Cosmos DB. In the recent times i started consuming Rest API for my hybrid application. One of the tricky part in Cosmos DB is that connecting to it and running queries with REST API. In this blog post, I want to elaborate more on the repository i have created to test the APIs in one go. Also will discuss more on how to call Azure Cosmos DB by using its REST API. I will be using the Cosmosdb account and Postman tool.

If you are very new to Cosmosdb, read my blog on how to setup Cosmos DB in local and connect via Visual Studio Code. Many of us come from the SQL background, when we want to connect to SQL Server, usually we need to have a username and password. You need to do more than that to connect and run queries in CosmosDB. But CosmosDB needs some more parameters to connect to it.

Once you create the Cosmos DB account on Azure and navigate to the keys section on the left pane. You will see two types of tabs on the Keys. There are two types of keys, one type of users having the Key can Read and Write. Other type ofusers having the key can only Read. 

Let's understand different terms used while making a connection to Cosmos DB

Master Keys are keys are created when the Cosmos DB Account is created. This key can be regenerated by clicking on refresh icon to regenerate them in the Azure portal. When you are using Cosmos DB emulator you won't be able to generate it. These keys are very sensitive ones and provide access to the administrative resources. We should be very careful when weneed to store them. Recommended way is to use Read-Only Keys as much as we can.

Resource Tokens are responsible for providing access to specific containers, documents, attachments, stored procedures, triggers, and UDFs. Each user must have a resource token. It is mandatory that every application needs to use a resource token to call Cosmos DB API.

Users are specific for Cosmos DB databases. You can attach specific permissions or roles to each user like the way we do in SQL server.

Cosmos DB API

As i mentioned earlier we have many options to access to CosmosDB. Rest API is one of these options and it is the low level access way to Cosmos DB. Most of the features supported with SDK are available and you can customize all options of CosmosDB by using REST API. To customize the calls, and pass the required authorization information, you need to use http headers.

In the following example, I am going to try to create a database in CosmosDB emulator by using the REST API. First let’s look at the required header fields for this request. These requirement applies to all other REST API calls too.

x-ms-version : As the name indicates this is the version of the REST API. You can find the available versions here. If you are confused on what to use always use the latest one.

x-ms-date : This is the date of your request. It must be formatted by Coordinated Universal Time. (ex: Sun, 30 June 2019 05:00:23 GMT)

x-ms-session-token: It is required if you want to use session consistency. For each of your new write request in Session consistency, CosmosDB assings a new SessionToken to the calls. You need to track the right session token and use it in this header property to keep usng the same session. SDK does this for you in the background, if you want to use the REST API, you need to do this manually.

Authorization: This one is the most important and tricky one. This needs to get generated for each of your call to Cosmos DB. It must be in the following format

How to Call APIs with Postman:

To call Cosmos DB directly from POSTMAN, you need to get the Cosmosdb account URL we need to use. If you are using the emulator, you can get it from the the local environment which should be like https://localhost:8081. I will be using the account created in Azure protal.

One other thing you need to setup is the environment variable as you see we are using some of the configured variables in the script, you can create a new environment variable using Postman by navigating to environments and add new environment with configured variables.

Create environments

Configured variables

we need to look at the documentation of CosmosDB Rest API. You can find all URL locations from this link. Since I am trying to list the databases inside a collection, I am going to use the following path.

https://postmandemo.documents.azure.com:443/

     Also, documentation tells us that this must be a GET Http Action. In Postman, I pick the GET and type the URL to the URL section in the following example.

As Next step, we need to create an environment in Postman to store some variables. As connecting to cosmos db needs a token we need to generate a token for CosmosDB and get the current date to fill the header named x-ms-date. I am going to use variables in Environment to store the values. To Create an environment. Click on gears icon and click on Add.

The below example shows the environment variables that we will frequently use to test Cosmos DB API.

As we are requesting to get the list of databases, we are ready to add values to headers section. Click on Headers link, and add the following headers. These are the required HTTP headers for all CosmosDB REST API calls.

x-ms-version : 2019-06-30
(This is the latest version. You can find the other versions here.)

x-ms-date: {{utcDate}}
(This is the variable we defined in the Postman environment. Its value will be generated dynamically in the Pre-request Script.)

authorization : {{authToken}} (This is the other parameter we just created. We are going to generate its value in script.)

Acceptapplication/json.
(This is required since this is going to be a GET Http Action.)

Your screen should looks like this.

Next, we need to generate an authorization token and the current date in the required format.
To do this, we’ll use the Pre-request Script section in Postman. This script runs automatically before each request. In this step, we’ll generate the authToken and utcDate parameters.
Simply copy and paste the following code into the Pre-request Script tab:

https://gist.github.com/sajeetharan/c2c1fbc48bf24e3b321323b34232f5a8

We are done with all the things needed to get the list of databases. Click on the send button to see the list of databases as response.

Great! Look at all that information we received back in the body of the Response.

This is the way to test Cosmos DB API with POSTMAN. You can try different APIs with the simple collection we've created here. Now it becomes easy for developers to leverage the Cosmos DB api and to play around with it.