قالب وردپرس درنا توس
Home / Tips and Tricks / How do you create an API server? – CloudSavvy IT

How do you create an API server? – CloudSavvy IT



Express JS logo

API servers are everywhere – every time you connect to or update a web application, your browser sends requests for the latest data. We’re going to take a look at how this is handled behind the scenes and how you can code your own API server.

What is an API server and how does it work?

Here is an example. You have a web application that needs to connect to a database and get some data, such as: B. Posts by users on a social media site. Obviously, users cannot connect directly to your database server as it is a major security flaw that leaves connection details in your app.

The solution is to put a server in the middle that takes requests from the user, interprets them, and then securely queries the database for the requested information. The user never needs to see the database. In fact, it is often run on a private subnet to prevent access to anything other than your API servers.

This allows clients to securely access your data via HTTP / HTTPS. Since the API server is owned and controlled by you, this connection is easier to secure. However, you still need authentication to verify that users are logged in as they say they are.

An API server setup

The API server is not meant to do the heavy lifting on your website. For most static content, you should use a traditional web server like NGINX, which is much more powerful. For example, you will serve index.html and bundle.js Use your NGINX server, which the client will unpack and run. The client-side JavaScript application then sends a request to the API server, which processes it from there.

You can create API servers in any language. All you need is the ability to listen to and respond to HTTP requests and connect to a database, both of which have many libraries for each language. In this guide we use JavaScript with Node.JS, use Express for HTTP and route handling. Another popular option for C # is ASP.NET from Microsoft.

If you work with AWS, check out the AWS GateWay API. Rather than running a full API server, API GateWay provides an inexpensive managed solution that can act as a front end to Lambda functions and RDS.

Set up an API server with Express.JS

Express.JS is a web application framework that runs on Node (server-side JavaScript). It is very easy to use and can be combined well with client-side JavaScript applications.

Create a new folder for the server and run it npm init to set up yours package.json. Create App.jsand paste the following:

const express = require('express')
const app = express()
const port = 3000

app.get("https://www.cloudsavvyit.com/", (req, res) => res.send('Message from Express route handler: Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

This is the basic requirement for a simple express server. The server itself is created with express(). Then routes and the associated handler functions are registered. In this case, app.get("https://www.cloudsavvyit.com/", handler) registers a handler function for GET requests on the / Route. There are other handler functions for the other HTTP verbs like POST and PUT.

In the handler is the req Object represents the HTTP request with res Present the answer. Then res.send sends back basic data like a string or a JSON object. You can also use Express as a conventional web server res.sendFileHowever, we recommend using a native object for performance with static objects.

At the beginning you can run node App.js, but nodemon is better as it monitors the base file for changes and automatically restarts.

npm i -g nodemon

nodemon app.js

When you visit localhost:3000 Express should respond to requests in your browser.

In addition to the functions for multiple handlers, you can also match many different routes. Explicit routing is easy –app.get('/users') processes inquiries to /users. You can also match routes with wildcards and regular expressions. You can even nest router handlers. For example, create a new handler specifically for a subdirectory like '/users'which is separate from the main app and is usually saved and exported from its own file.

However, all of this is still served over HTTP, so the first upgrade is to set up HTTPS. This is easy to use; All you need is your private SSL key and your certificate. If you’re just testing, you can use to create a self-signed certificate openssl::

openssl req -nodes -new -x509 -keyout server.key -out server.cert

You’ll have to manually trust this certificate when Chrome freaks out, but it will work. Instead of calling, listen appWe set up the HTTPS server, hand it over the app and listen to it.

const express = require('express')
var https = require('https')
var fs = require('fs')

const app = express()
const port = 3000

app.get("https://www.cloudsavvyit.com/", (req, res) => res.send('Message from Express route handler: Hello World!'))

https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
  }, app)
  .listen(port, () => console.log(`Example app listening on port ${port}!`))

Connecting a database

This step depends on your specific database, but it’s actually nothing special. All you have to do is install the Node.JS driver for your database, provide Express connection details, and connect to it as you would with normal JavaScript (or any other language you use to build your API Servers) would do.

In this guide, we’ll use MongoDB, a JSON document database that is often paired with Express. If you have Docker, you can run it in a container for testing:

docker run -d -p 27017-27019:27017-27019 --name mongodb mongo:4.0.4

You can use MongoDB Compass to connect and perform administrative tasks.

On the express side, you need to install the MongoDB NPM package in order to connect.

npm install mongodb

Since Express should only be started after connecting the database, we will move app.listen() Inside MongoClient.connect().

const express = require('express')
var https = require('https')
var fs = require('fs')
const MongoClient = require('mongodb').MongoClient

const app = express()
const port = 3000

app.get("https://www.cloudsavvyit.com/", (req, res) => res.send('Message from Express route handler: Hello World!'))

var db;
MongoClient.connect('mongodb://localhost:27017/', (err, client) => {
  if (err) return console.log(err)
    db = client.db('test') // whatever your database name is

  https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
  }, app)
  .listen(port, () => console.log(`Example app listening on port ${port}!`))
})

Now you can use the to connect to Mongo db Variable and all standard methods. You should make sure you are using async / await or you will return untreated promises.

app.get("https://www.cloudsavvyit.com/", async (req, res) => {
  const response = await db.collection('test').find().toArray();
  res.send(response)
})

This connects to the database and returns the contents of the test Collection and spit it out as a JSON array.

Since Express is just the front end for these functions, you don’t have to define all of your logic in this one file. You can break them up into modules and import whatever you need to call from the express route handlers.

Caching API performance requirements

Express isn’t the fastest thing. If you plan to use it in production, you will likely want to implement some form of caching so that you don’t have to do expensive searches for repeatable requests.

Note that you should never cache anything that requires authentication to be viewed, such as: B. the personal information of a user. The general rule is, if the page is the same for everyone, you can cache it for everyone. PUT, DELETE, and POST methods should never be cached.

You can use in-memory storage like Redis for this, but a simple memory cache works pretty well. To install memory-cache from npm::

npm i memory-cache

Then in App.jsBefore your routes, create a new caching middleware:

const cache = require('memory-cache');

let memCache = new cache.Cache();
let cacheMiddleware = (duration) => {
  return (req, res, next) => {
    let key = '__express__' + req.originalUrl || req.url;
    let cacheContent = memCache.get(key);
    if(cacheContent){
      res.send( cacheContent );
      return;
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        memCache.put(key,body,duration*1000);
        res.sendResponse(body);
      }
      next()
    }
  }
}

On the routes that you can cache, you can use this middleware before the primary handler to cache the results X Seconds:

app.get('/products', cacheMiddleware(30), function(req, res){
  ...
});

Source link