Ben Taylor

Ben Taylor

1583304787

How to Build a Web API with NodeJS, Express and MySQL

Introduction

In this post, we are going to create a Web API with the help of node.js, Express, and MySQL. Web API is an application which serves HTTP based requests by different applications on different platforms, such as web, Windows, and mobile.

Requirements

  1. MySQL
  2. NodeJS
  3. Active Internet
  4. Postman Application
  5. Visual Studio Code

Step 1

Create a database in MySQL, named sampledb and use it.

mysql> create database sampledb;  
mysql> use sampledb;  

Step 2

Create a new table named employee.

mysql> create table employee  
         (  
        id int primary key,  
        name varchar(20),  
        gender varchar(20),  
        city varchar(20),  
        salary int  
);  

Step 3

Add some rows to the table.

mysql> insert into employee values(1,'pankaj','male','delhi',15000);  
mysql> insert into employee values(2,'pooja','female','pune',25000); 

Step 4

Open command prompt/cmd and navigate to the application folder, i.e., webapi.

C:\Users\Pankaj Singh\Desktop\webapi>

Step 5

Initialize the app with npm init,

C:\Users\Pankaj Singh\Desktop\webapi>npm init

This is image title

Step 6

Now, add some Node modules, as mentioned below.

C:\Users\Pankaj Singh\Desktop\webapi>npm install express
C:\Users\Pankaj Singh\Desktop\webapi>npm install mysql
C:\Users\Pankaj Singh\Desktop\webapi>npm install body-parser

Step 7

Add a server.js file to the application.

C:\Users\Pankaj Singh\Desktop\webapi>null>server.js

Step 8

Open Visual Studio Code.

C:\Users\Pankaj Singh\Desktop\webapi>code .

This is image title

Step 9

Our package.json file looks like this.

This is image title

Step 10

Now, configure the server.js file. Basic Express app is as follows

var express = require('express');  
var mysql = require('mysql');  
var bodyParser=require('body-parser');  
  
var urlencoderParser = bodyParser.urlencoded({extended:false});  
  
var app=express();  
var port = process.env.port||3000;  
  
//Api code here  
  
app.listen(port);  
console.log('Server is started on http://localhost:'+port);  

Step 11

Add a connection to MySQL.

//Mysql Connection  
var con = mysql.createConnection({  
    host:'localhost',  
    user:'root',  
    password:'password0',  
    database:'sampledb'  
});  

Step 12

Now, add code for GET request on root “/api” . This route returns all the rows of employee table.

//GET  
app.get('/api',function(req,res){  
    var qry = "select * from employee";  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log(rows);  
        res.json(rows);  
    });  
});  

Step 13

Add code for GET request with id on root “/api/”. This route returns the row of employee table with the given id

//GET with id  
app.get('/api/:id',function(req,res){  
    var qry = "select * from employee where id="+req.params.id;  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log(rows[0]);  
        res.json(rows[0]);  
    });  
});  

Step 14

Now, add code for POST request. In this request, we use urlencoderParser to read the body content of the request.

//POST  
app.post('/api',urlencoderParser,function(req,res){  
    var qry = "insert into employee values("+parseInt(req.body.id)+",'"+req.body.name+"','"+req.body.gender+"','"+req.body.city+"',"+parseInt(req.body.salary)+")";  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log("1 Row Added.");  
        res.send("1 Row Added.")  
    });  
});  

Step 15

Now, add code for POST request. In this request, we use urlencoderParser to read the body content of the request.

//PUT  
app.put('/api/:id',urlencoderParser,function(req,res){  
    var qry = "update employee set name='"+req.body.name+"',gender='"+req.body.gender+"',city='"+req.body.city+"',salary="+parseInt(req.body.salary)+" where id="+parseInt(req.params.id);  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log("1 Row Updated.");  
        res.send("1 Row Updated.")  
    });  
});  

Step 16

Add the code for DELETE Request.

//DELETE  
app.delete('/api/:id',function(req,res){  
    var qry = "delete from employee where id="+parseInt(req.params.id);  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log("1 Row Removed.");  
        res.send("1 Row Removed.")  
    });  
});  

Step 17

The complete code is as follows.

var express = require('express');  
var mysql = require('mysql');  
var bodyParser=require('body-parser');  
  
var urlencoderParser = bodyParser.urlencoded({extended:false});  
  
var app=express();  
var port = process.env.port||3000;  
  
//Api code here  
  
//Mysql Connection  
var con = mysql.createConnection({  
    host:'localhost',  
    user:'root',  
    password:'password0',  
    database:'sampledb'  
});  
  
//GET  
app.get('/api',function(req,res){  
    var qry = "select * from employee";  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log(rows);  
        res.json(rows);  
    });  
});  
  
//GET with id  
app.get('/api/:id',function(req,res){  
    var qry = "select * from employee where id="+req.params.id;  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log(rows[0]);  
        res.json(rows[0]);  
    });  
});  
  
//POST  
app.post('/api',urlencoderParser,function(req,res){  
    var qry = "insert into employee values("+parseInt(req.body.id)+",'"+req.body.name+"','"+req.body.gender+"','"+req.body.city+"',"+parseInt(req.body.salary)+")";  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log("1 Row Added.");  
        res.send("1 Row Added.")  
    });  
});  
  
//PUT  
app.put('/api/:id',urlencoderParser,function(req,res){  
    var qry = "update employee set name='"+req.body.name+"',gender='"+req.body.gender+"',city='"+req.body.city+"',salary="+parseInt(req.body.salary)+" where id="+parseInt(req.params.id);  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log("1 Row Updated.");  
        res.send("1 Row Updated.")  
    });  
});  
  
//DELETE  
app.delete('/api/:id',function(req,res){  
    var qry = "delete from employee where id="+parseInt(req.params.id);  
    con.query(qry,function(err,rows){  
        if(err)  
            throw err;  
        console.log("1 Row Removed.");  
        res.send("1 Row Removed.")  
    });  
});  
  
app.listen(port);  
console.log('Server is started on http://localhost:'+port);  

Step 18

Now, Run the API.

C:\Users\Pankaj Singh\Desktop\webapi>nodemon server.js
[nodemon] 1.19.1
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node server.js

Server is started on http://localhost:3000

Step 19

Open Postman to test the API.

This is image title

Step 20

Sending GET Request to API. In response, we get all the rows of the employee table as JSON data.

This is image title

Step 21

Sending GET Request with Id to API. In response, we get all the row of the employee table with given id as JSON data.

This is image title

Step 22

Sending POST Request with the body to API.

This is image title

Step 23

Sending put request with the body to API.

This is image title

Step 24

Sending put request with the body to API.

This is image title

Thank you for reading!

#node-js #webapi #express #mySQL

What is GEEK

Buddha Community

How to Build a Web API with NodeJS, Express and MySQL
Joe  Hoppe

Joe Hoppe

1595905879

Best MySQL DigitalOcean Performance – ScaleGrid vs. DigitalOcean Managed Databases

HTML to Markdown

MySQL is the all-time number one open source database in the world, and a staple in RDBMS space. DigitalOcean is quickly building its reputation as the developers cloud by providing an affordable, flexible and easy to use cloud platform for developers to work with. MySQL on DigitalOcean is a natural fit, but what’s the best way to deploy your cloud database? In this post, we are going to compare the top two providers, DigitalOcean Managed Databases for MySQL vs. ScaleGrid MySQL hosting on DigitalOcean.

At a glance – TLDR
ScaleGrid Blog - At a glance overview - 1st pointCompare Throughput
ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads. Read now

ScaleGrid Blog - At a glance overview - 2nd pointCompare Latency
On average, ScaleGrid achieves almost 30% lower latency over DigitalOcean for the same deployment configurations. Read now

ScaleGrid Blog - At a glance overview - 3rd pointCompare Pricing
ScaleGrid provides 30% more storage on average vs. DigitalOcean for MySQL at the same affordable price. Read now

MySQL DigitalOcean Performance Benchmark
In this benchmark, we compare equivalent plan sizes between ScaleGrid MySQL on DigitalOcean and DigitalOcean Managed Databases for MySQL. We are going to use a common, popular plan size using the below configurations for this performance benchmark:

Comparison Overview
ScaleGridDigitalOceanInstance TypeMedium: 4 vCPUsMedium: 4 vCPUsMySQL Version8.0.208.0.20RAM8GB8GBSSD140GB115GBDeployment TypeStandaloneStandaloneRegionSF03SF03SupportIncludedBusiness-level support included with account sizes over $500/monthMonthly Price$120$120

As you can see above, ScaleGrid and DigitalOcean offer the same plan configurations across this plan size, apart from SSD where ScaleGrid provides over 20% more storage for the same price.

To ensure the most accurate results in our performance tests, we run the benchmark four times for each comparison to find the average performance across throughput and latency over read-intensive workloads, balanced workloads, and write-intensive workloads.

Throughput
In this benchmark, we measure MySQL throughput in terms of queries per second (QPS) to measure our query efficiency. To quickly summarize the results, we display read-intensive, write-intensive and balanced workload averages below for 150 threads for ScaleGrid vs. DigitalOcean MySQL:

ScaleGrid MySQL vs DigitalOcean Managed Databases - Throughput Performance Graph

For the common 150 thread comparison, ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads.

#cloud #database #developer #digital ocean #mysql #performance #scalegrid #95th percentile latency #balanced workloads #developers cloud #digitalocean droplet #digitalocean managed databases #digitalocean performance #digitalocean pricing #higher throughput #latency benchmark #lower latency #mysql benchmark setup #mysql client threads #mysql configuration #mysql digitalocean #mysql latency #mysql on digitalocean #mysql throughput #performance benchmark #queries per second #read-intensive #scalegrid mysql #scalegrid vs. digitalocean #throughput benchmark #write-intensive

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api