HTTP server for Deno with local JSON REST API for rapid prototyping

Tino

HTTP server for Deno with local JSON REST API for rapid prototyping.

Install and Use

  1. Install Deno: https://deno.land/#installation
  2. Try it out: $ deno run --allow-net --allow-read --allow-write https://deno.land/x/tino@v1.0.5/tino.js

Internally Tino uses jsondb responder which opens /api path for playing around. It uses db.json file by default as a database.

  1. To see it already, copy it from tests: $ cp ./tests/jsondb.test.json ./db.json
  2. Open http://localhost:8000/api

Run tests

Run: $ deno test

All tests are included in ./tests directory.

Minimal configuration (custom endpoints)

// app.js
import tino from "https://deno.land/x/tino@v1.0.5/tino.js";
const app = tino.create();
const controller = () => ({ resp: "pong", status: 200 }) // must return { resp, status?, type? }
app.get(() => ({ path: "/ping", use: controller }));
tino.listen({ app, port: 8000 });
console.log(`Server running at 8000`);
  1. Now run the server: $ deno run --allow-net app.js
  2. Send a request: $ http :8000/ping (HTTPie, curl, Postman, etc.)
  3. Receive "pong" as text/plain content type

Further configurations

// Shorter: Use `resp` directly with status 200
app.get(() => ({ path: "/ping", resp: "pong" }));

// `resp` can be anything:
app.get(() => ({ path: "/ping", use: () => ({ resp: () => "pong", status: 200 }) }));

// Or (use: can also be async)
app.get(() => ({ path: "/ping-async", use: () => ({ resp: async () => "pong", status: 201 }) }));
app.not_found(() => ({ resp: "Oops" }));

Tino application app supports following HTTP methods: GET, POST, PUT, PATCH, DELETE. Method names are lowercased. Also there is not_found for status 404, so you can define custom response.

resp can be anything, but if it’s a function it will return it’s result of execution, and it will be called no matter if it’s async or not. If it’s an object (or returned as an object), content type will be application/json.

The only requirement for controller use is that it must return { resp, status?, type? } object. It can also be defined as async function.

Difference between Tino and “usual approach”

What I’ve seen and used is that usually there are one or more global variables or internally modified variables through the request cycle. This results in following pseudo code:

myController = ctx => {
  ctx.type = "text/html";
  ctx.status = 200;
  ctx.body = "<p>Greetings!</p>";
}

While in Tino idea is that all functions are composed and there is no global variable but what you want in next step is what you pass further, through the chain. That might look like:

myController = () => {
  const type = "text/html";
  const status = 200;
  const body = "<p>Greetings!</p>";
  return { type, status, body };
}

If you read further on about middlewares for example you’ll see how this plays well with composition. These functions must be pure, easy to unit test and able to be recursive.

Defining path parameters

Parameters are defined as :param in your path definition. Optionals are defined as :param?. Some examples:

app.get(() => ({ path: "/user/:id", use: () => ({ resp: ({ params }) => params.id }));
app.get(() => ({ path: "/notes/:id?", use: () => ({ resp: ({ params, notes }) => params.id ? [] : notes }));

props definition

If defined as a function, resp receives following parameters:

  1. body - body payload for POST, PUT or PATCH methods
  2. params - parameters from path definition, e.g. /path/:id
  3. query - query object from string like ?p=1&q=2
  4. custom params - anything else provided to method definition, except path, resp or use
  5. matchedPath - information about path regex
  6. pathPattern - information about path definition
  7. req - in form of { method, url }
  8. Any other parameters coming from middlewares

Basically you can test this with following have-it-all definition:

// $ http POST :8000/post/123?q=1 foo=bar
const composed = withMiddlewares(
  () => ({ isAdmin: true }),
);
app.post(() => ({
  path: "/post/:id", // or optional with :id?
  use: composed((props) => ({ resp: { ...props } })),
  something: "else",
}));

Response

Response received should be:

{
  "body": {
    "foo": "bar"
  },
  "isAdmin": true,
  "matchedPath": {
    "index": 0,
    "params": {
      "id": "123"
    },
    "path": "/post/123"
  },
  "params": {
    "id": "123"
  },
  "pathPattern": "/post/:id",
  "query": {
    "q": "1"
  },
  "something": "else"
}

Return type (Content type)

When you define resp, you can define content type such as text/html:

const use = () => ({ resp: "<p>Works!</p>", status: 200, type: 'text/html' });
app.get(() => ({ path: "/ping", use  }));

Middlewares

Middlewares offer you way to extend response by injecting additional information to your controllers. In Tino it is done by async functional composition so your middlewares can be both sync and async. It is offered by withMiddlewares helper from tino.js.

Examples:

  1. Check if user is admin and inject database into your controller:
import { withMiddlewares } from "tino.js";
// Initial props are provided: https://github.com/Vertrical/tino#props-definition
const auth = (props) => ({ isUser: true });
const isAdmin = (props) => ({ isAdmin: false, ...props });
const withDB = (props) => ({ coll: {}, ...props });
const composed = withMiddlewares(auth, isAdmin, withDB);
// Define your endpoint:
const use = composed(({ isUser, isAdmin, coll }) => ({ resp: "Hello", status: /*...*/ }));
app.get(() => ({ path: "/ping", use }));

Any prop that is returned will be passed over to next function in chain, until the end - end result is what is passed to your controller.

  1. Exit early depending on if a precondition hasn’t been met (protect the router):

It’s similar to previous case only that if any of the middlewares throws an exception it will be used as end result of your controller, i.e. replace it.

import { withMiddlewares } from "tino.js";
const auth = (props) => { throw { resp: "Boom", status: 401 }; };
const isAdmin = (props) => ({ isAdmin: false, ...props });
const withDB = (props) => ({ coll: {}, ...props });
const composed = withMiddlewares(auth, isAdmin, withDB);
// Define your endpoint:
const use = composed(({ isUser, isAdmin, coll }) => ({ resp: "Hello" }));
app.get(() => ({ path: "/ping", use }));
// HTTP Response headers and content: (if you call "localhost:{port}/ping)
`
HTTP/1.1 401 Unauthorized
content-length: 4
content-type: text/plain

Boom
`

Note: Whatever you want to be returned from middlewares to your controller, you should propagate these props through the chain. (As seen above with ...props for example)

Responders

In Tino responders are your implementations of custom APIs which don’t rely on paths pattern matching.

You define a responder by adding root: true to your endpoint definition.

For example:

import myAwesomeAPI, { v2 } from "somewhere";
app.any(() => ({ path: "/awesome-api", use: myAwesomeAPI, root: true })); // <-- Notice the `root: true` part
app.any(() => ({ path: "/awesome-api/v2", use: v2, root: true }));

Setting the root part is because we will match here only by startsWith against your request, disregarding any parameter matching.

Example of a responder is jsondb which comes integrated with Tino and is located in jsondb.js file.

Using jsondb responder

This responder is just a small package included by default in Tino which handles CRUD operations on db.json file.

Each response is wrapped with response parent, like:

// GET /api/users/1234
{
  "response": {
    "id": "1234",
    "name": "Smith"
  }
}

How is jsondb responder defined?

jsondb responder is already integrated with Tino so you don’t need to do anything. But, if you want to define it nevertheless, you can do it like below:

import tino, { jsondb } from "tino.js";
const app = tino.create();
app.any(() => ({ path: "/api", use: jsondb(), root: true })); // notice the ()
// If you want some other namespace
app.any(() => ({ path: "/awesome-api", use: jsondb(), root: true }));
tino.listen({ app });

(Please note that jsondb must be called. This is because it is a higher order function.)

any is needed because we want ANY HTTP METHOD to be used with this.

JSON REST API

Test JSON file is included in tests/jsondb.test.json. You need to create your ./db.json file to operate agains it.

Having the content same as in jsondb.test.json file, we would have following requests returning respective responses:

# Get list of items:
$ http :8000/api/laptops

# Get item by id: (jsondb treats any "id" found in an entity as ID)
$ http :8000/api/laptops/123

# Create new item:
$ http POST :8000/api/laptops id=789 brand=apple

# Replace an item:
$ http PUT :8000/api/laptops/789 brand=asus

# Update an item:
$ http PATCH :8000/api/laptops/789 brand=asus

# DELETE an item:
$ http DELETE :8000/api/laptops/789

You can see many examples in tests/requests.http file.

Customize API

If you want to change endpoint from /api to something else, just replace it:

app.any(() => ({ path: "/myapi", use: jsondb(), root: true }));

// you can optionally "close" /api
app.any(() => ({ path: "/api", status: 404 }));

Remember that you need to create file db.json yourself. If not, the response will be empty and status 404.

CLI and options for Tino and jsondb

Dry run for jsondb

If you want only to check how a request would modify db.json database without touching it, you can do a dry run.

# --allow-write is not necessary
deno run --allow-net --allow-read tino.js --dry=true

In your code you can achieve same by passing true to jsondb responder:

app.get(() => ({ path: "/ping", use: jsondb(true), root: true }));

Custom port

You can run Tino on custom port:

deno run --allow-net --allow-read --allow-write tino.js --port=7000

Similarly, in your code you can pass it to listen method:

// if you omit port, it will be 8000
tino.listen({ app, port: 7777 });

Examples

You can find maintained list of exampes in examples.js file.

To-do list

  • [ ] Write TypeScript support (depends on https://github.com/microsoft/TypeScript/issues/38510)
  • [ ] The “after hooks”, similar to middlewares but happening AFTER your controller
  • [ ] Cookies support
  • [ ] GraphQL responder for local prototyping (like jsondb for REST)

Download Details:

Author: Vertrical

Source Code: https://github.com/Vertrical/tino

#deno #node #nodejs #javascript

What is GEEK

Buddha Community

HTTP server for Deno with local JSON REST API for rapid prototyping
Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

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

Lets Cms

Lets Cms

1652251528

Opencart REST API extensions - V3.x | Rest API Integration, Affiliate

Opencart REST API extensions - V3.x | Rest API Integration : OpenCart APIs is fully integrated with the OpenCart REST API. This is interact with your OpenCart site by sending and receiving data as JSON (JavaScript Object Notation) objects. Using the OpenCart REST API you can register the customers and purchasing the products and it provides data access to the content of OpenCart users like which is publicly accessible via the REST API. This APIs also provide the E-commerce Mobile Apps.

Opencart REST API 
OCRESTAPI Module allows the customer purchasing product from the website it just like E-commerce APIs its also available mobile version APIs.

Opencart Rest APIs List 
Customer Registration GET APIs.
Customer Registration POST APIs.
Customer Login GET APIs.
Customer Login POST APIs.
Checkout Confirm GET APIs.
Checkout Confirm POST APIs.


If you want to know Opencart REST API Any information, you can contact us at -
Skype: jks0586,
Email: letscmsdev@gmail.com,
Website: www.letscms.com, www.mlmtrees.com
Call/WhatsApp/WeChat: +91–9717478599.

Download : https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=43174&filter_search=ocrest%20api
View Documentation : https://www.letscms.com/documents/api/opencart-rest-api.html
More Information : https://www.letscms.com/blog/Rest-API-Opencart
VEDIO : https://vimeo.com/682154292  

#opencart_api_for_android #Opencart_rest_admin_api #opencart_rest_api #Rest_API_Integration #oc_rest_api #rest_api_ecommerce #rest_api_mobile #rest_api_opencart #rest_api_github #rest_api_documentation #opencart_rest_admin_api #rest_api_for_opencart_mobile_app #opencart_shopping_cart_rest_api #opencart_json_api

Lets Cms

Lets Cms

1652251629

Unilevel MLM Wordpress Rest API FrontEnd | UMW Rest API Woocommerce

Unilevel MLM Wordpress Rest API FrontEnd | UMW Rest API Woocommerce Price USA, Philippines : Our API’s handle the Unilevel MLM woo-commerce end user all functionalities like customer login/register. You can request any type of information which is listed below, our API will provide you managed results for your all frontend needs, which will be useful for your applications like Mobile App etc.
Business to Customer REST API for Unilevel MLM Woo-Commerce will empower your Woo-commerce site with the most powerful Unilevel MLM Woo-Commerce REST API, you will be able to get and send data to your marketplace from other mobile apps or websites using HTTP Rest API request.
Our plugin is used JWT authentication for the authorization process.

REST API Unilevel MLM Woo-commerce plugin contains following APIs.
User Login Rest API
User Register Rest API
User Join Rest API
Get User info Rest API
Get Affiliate URL Rest API 
Get Downlines list Rest API
Get Bank Details Rest API
Save Bank Details Rest API
Get Genealogy JSON Rest API
Get Total Earning Rest API
Get Current Balance Rest API
Get Payout Details Rest API
Get Payout List Rest API
Get Commissions List Rest API
Withdrawal Request Rest API
Get Withdrawal List Rest API

If you want to know more information and any queries regarding Unilevel MLM Rest API Woocommerce WordPress Plugin, you can contact our experts through 
Skype: jks0586, 
Mail: letscmsdev@gmail.com,
Website: www.letscms.com, www.mlmtrees.com,
Call/WhatsApp/WeChat: +91-9717478599.  

more information : https://www.mlmtrees.com/product/unilevel-mlm-woocommerce-rest-api-addon

Visit Documentation : https://letscms.com/documents/umw_apis/umw-apis-addon-documentation.html

#Unilevel_MLM_WooCommerce_Rest_API's_Addon #umw_mlm_rest_api #rest_api_woocommerce_unilevel #rest_api_in_woocommerce #rest_api_woocommerce #rest_api_woocommerce_documentation #rest_api_woocommerce_php #api_rest_de_woocommerce #woocommerce_rest_api_in_android #woocommerce_rest_api_in_wordpress #Rest_API_Woocommerce_unilevel_mlm #wp_rest_api_woocommerce

Adonis  Kerluke

Adonis Kerluke

1596509565

RESTful API Design Driven Approach

In this tutorial I will show you the fundamentals of designing a RESTful API specification by applying REST principles and best practices, then you’ll be ready to try my online tutorial: How to design a REST API with API Designer?

If you already know what is meant by API in the context of RESTful web services, you can skip to the next section. If not, read on.

Level-Set on API

The abbreviation API stands for Application Programming Interface this in itself, does not help us understand what it is, however in the context of web services, it can refer to one of two things:

  1. The RESTful API specification is written using a modeling language such as Open API specification or RAML (RESTful API Modeling Language) that defines a contract for how software components can interact with a service.
  2. The implementation of a web service or microservice whose contract is designed by REST principles that describe how other services must interact with it.

In this post, I will use the first understanding of this term. Even though both are correct, the most technically relevant for this post is the first: an API is a contract for how software applications talk to each other.

Level-Set on REST

The acronym REST stands for REpresentational State Transfer. It is an architectural style used to represent the transmission of data from one application component to another. In the context of web services, we are talking about the representation of resources (i.e. data) transferred over HTTP by calling a URI that represents the data and via an HTTP method that represents the action to perform against the given data.

What Is RESTful API design?

RESTful API design is the activity of describing the behavior of a web service in terms of its data structures and the actions you allow other application components to perform on its data by the principles of REST. Those principles are covered later in this blog.

Why Design a RESTful API?

Imagine that you are an Architect (the kind the design building) and you set out to build an office block without a blueprint. You turn up on the first day with a truck full of bricks and some cement. What are the chances that you’ll be successful and build a structure that conforms to code and more importantly, doesn’t fall? It’s about zero. Without a blueprint the chance of failure is high.

The same approach applies to web service development. You need a blueprint, or more appropriately, an API specification. This is necessary to evaluate the API design and solicit feedback before even starting to build the implementation.

In addition to providing a specification for the web service’s development, an API contract serves to document its expected behavior, data types, and security requirements.

You should now be satisfied that API design is necessary for a RESTful web service, and should start to wonder how is the best approach to actually designing an API specification.

API Design Tooling

The tooling chosen by an API designer has substantial influence over the designer’s productivity. Highly productive tools such as the Anypoint API Designer from MuleSoft is perfect for designing APIs with OAS (swagger) or RAML.

#integration #api #rest #rest api #restful #api design #raml #rest api design