Elegant and simple way to build requests for REST API

Elegant and simple way to build requests for REST API

This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated classes. Keep your code clean and elegant.

If you use Laravel, this package matches perfectly with spatie/laravel-query-builder.

Basic usage

Give me the result for a given criteria, include some entities, append extra fields and order the result!

// GET /posts?filter[status]=ACTIVE&include=user,category&append=likes&orderBy=-created_at,category_id

let posts = await Post
  .where('status', 'ACTIVE')
  .include('user', 'category')
  .append('likes')
  .orderBy('-created_at', 'category_id')  
  .get()

Just give me the first occurrence from response:

// GET /posts?filter[status]=ACTIVE

let post = await Post
  .where('status', 'ACTIVE')
  .first()

Nice! Now I want a specific object:

// GET /posts/1

let post = await Post.find(1)

Edit this and send it back:

// PUT /posts/1 

post.title = 'Awsome!'
post.save()

Ops, delete it!

// DELETE /posts/1

post.delete()

Let’s create a new object and post it:

let post = new Post({title: 'Cool!'})

// or

let post = new Post({})
post.title = 'Another one'

// POST /post

post.save()

We can use relationships:

// GET /users/1
let user = await User.find(1)

// GET users/1/posts
let posts = await user
  .posts()
  .get()

Installation

yarn add vue-api-query

NUXT

Create a plugin ~/plugins/vue-api-query.js

// inject global axios instance as http client to Model  

import { Model } from 'vue-api-query'

export default function (ctx, injext) {  
  Model.$http = ctx.$axios
}

And register it on nuxt.config.js

plugins: [
  '~plugins/vue-api-query'
]

VUE

Set up on src/main.js

[...]

import axios from 'axios'
import { Model } from 'vue-api-query'

// inject global axios instance as http client to Model
Model.$http = axios

[...]

Configuration

Define a base model

Your base model should extend from vue-api-query Model. Use base models is good practice in order to abstract configurations from your domain models.

models/Model.js

import { Model as BaseModel } from 'vue-api-query'

export default class Model extends BaseModel {

  // define a base url for a REST API
  baseURL () {
    return 'http://my-api.com'
  }

  // implement a default request method 
  request (config) {
    return this.$http.request(config)
  }
}

Define your domain models

Just extends from your base model, implement the resource() method… and done!

models/User.js

import Model from './Model'

export default class User extends Model {
  resource()
  {
    return 'users'
  }
}

But, if your model does not work with default primary key (‘id’),you need to override the primaryKey() method:

import Model from './Model'

export default class User extends Model {
  primaryKey()
  {
    return 'someId'
  }
}

Of course you can add extra methods and computed properties like this:

import Model from './Model'

export default class User extends Model {

  // computed properties are reactive -> user.fullname
  // make sure to use "get" prefix 
  get fullname()
  {
    return `${this.firstname} ${this.lastname}`
  }

  // method -> user.makeBirthday()
  makeBirthday()
  {
    this.age += 1
  }

}

You can set up relationships:

import Model from './Model'
import Post from './Post'

export default class User extends Model {

  posts () {
    return this.hasMany(Post)
  }
}

It’s ok if in some situations you need to call a custom resource from a already defined model. You can override dynamically the default resource calling custom() method.

// GET /posts
let posts = await Post.get()

// GET /posts/latest
let latest = await Post
  .custom('posts/latest')
  .first()  

The custom() method can be called with multiple arguments to build resource endpoints and hierarchies. Simply supply them in the correct order. Any combination of strings and models is possible.

    let user = new User({ id: 1 })
    let post = new Post()

    // GET /users/1/posts/latest
    const result = await Post.custom(user, post, 'latest').get()

Full example

/models/Post.js

import Model from './Model'

export default class Post extends Model {
  // done :)
  resource()
  {
    return 'posts'
   }
}

/models/User.js

import Model from './Model'
import Post from './Post'

export default class User extends Model {  
  resource()
  {
    return 'users'
  }

  posts () {
    return this.hasMany(Post)
  }

  // computed properties :)
  get fullname()
  {
    return `${this.firstname} ${this.lastname}`
  }

  // methods :)
  makeBirthday()
  {
    this.age += 1
  }
}

If the backend responds with …

// response from API for /users/1
{
  id: 1,
  firstname: "John",
  lastname: "Doe",
  age: 25
}

We can do this:

//GET /users/1
let user = await User.find(1)

console.log(user.fullname) // John Doe

user.makeBirthday()
user.save()

Then save() method will send back the new payload:

// PUT /users/1
{
  firstname: "John",
  lastname: "Doe",
  age: 26 //<--- changed
}

You also can do that:

//GET /posts?filter[status]=ACTIVE,ARCHIVED

let posts = await Post
  .whereIn('status', ['ACTIVE', 'ARCHIVED'])
  .get()

If you like the “promise way” just do it like this:

// single object

let user

User
  .where('status', 'ACTIVE')
  .first()
  .then(response => {
    user = response
  })

// array of objects

let users

User
  .where('status', 'ACTIVE')
  .get()
  .then(response => {
    users = response

    // or (depending on backend response)

    users = response.data 
  })

And in some page/component:

<template>
  User: 
  <code>
    {{ user }}
  </code>

  Posts from user:
  <code>
    {{ posts }}
  </code>
</template>
<script>
import User from '@/models/User'

export default {
  data()
  {
    return {
      user: {},
      posts: {}
    }
  },
  async mounted()
  {
    this.user = await User.find(1)
    this.posts = await this.user.posts().get()
  }
}
</script>

Relationships

// GET /users/1
let user = await User.find(1)

// GET /users/1/posts
let posts = await user.posts().get()

// Yes, you can do that before getting the posts
let posts = await user
  .posts()
  .where(...)
  .append(...)
  .include(...)
  .orderBy(...)
  .get()

If you like nested relationships …

// GET /posts/{id_post}/comments

let comments = await this.post.comments().get()

// Pick any comment from list and edit it

let comment = comments[0]
comment.text = 'Changed!'

// PUT /posts/{id_post}/comments/{id_comment}

await comment.save() 

// DELETE /posts/{id_post}/comments/{id_comment}

await comment.delete() 

Creating new related objects is easy. Just use the for() method, passing the related object.

  let post = new Post({title: 'Woo!'})  

  // POST /posts
  await post.save()

  let comment = new Comment({text: 'New one for this post'}).for(post)

  // POST /posts/1/comments
  await comment.save()

The for() method can take multiple objects to build hierarchy levels.

  let user = new User({id: 1})
  let post = await user.posts().first()

  // Related objects go in order of their appearance in the URL.
  let comment = new Comment({text: 'for() takes multiple objects.'}).for(user, post)

  // POST /users/1/posts/1/comments
  await comment.save()

If you need to get a nested resource, without getting the parent model at first, you can do something like this.

// GET /users/1/posts

let User = new User({id: 1})
let Post = await User.posts().get()

// GET /users/1/posts/2
let User = new User({id: 1})
let Post = await User.posts().find(2)

And just for convenience you can POST or PUT with any payload to backend:

// POST /posts/{id_post}/comments

await this.posts.comments().attach(payload) 

// PUT /posts/{id_post}/comments

await this.posts.comments().sync(payload) 

Pagination

// GET /users?sort=firstname&page=1&limit=20

let users = await User        
        .orderBy('firstname')
        .page(1) 
        .limit(20)
        .get()

Selecting fields

Just want only some fields?

// GET posts?fields[posts]=title,content

let post = await Post
   .select(['title', 'content'])
   .get() 

With related entities:

// GET posts?include=user&fields[posts]=title,content&fields[user]=firstname,age

let post = await Post
   .select({
      posts: ['title', 'content'],
      user: ['age', 'firstname']
    })
   .include('user')
   .get() 

TIP: If you are using spatie/laravel-query-builder, when using related entities, you must pass extra fields:

// GET posts?include=user&fields[posts]=title,content,user_id&fields[user]=id,firstname,age

let post = await Post
   .select({
      posts: ['title', 'content', 'user_id'],  //user_id
      user: ['id', 'age', 'firstname']         //id
    })
   .include('user')
   .get() 

Custom params

If you need to pass any extra param not provided by vue-api-query pattern, just use the params() method while querying:

// GET /users?doSomething=yes&process=no

let users = await User
  .params({
    doSomething: 'yes',
    process: 'no'
  })
  .get()

Of course you can chain it with other methods, including on relationships.

// GET /posts/1/comments?include=user&blah=123

let comments = await post
  .comments()
  .include('user')
  .params({blah: 123})
  .get()

Customize query parameters name

If you need to change default values just override parametersName() on your Base Model. So, the generated query string will use this new values.

models/Model.js

import { Model as BaseModel } from 'vue-api-query'

export default class Model extends BaseModel {

  parameterNames () {
    return {
      include: 'include_custom',
      filter: 'filter_custom',
      sort: 'sort_custom',
      fields: 'fields_custom',
      append: 'append_custom',
      page: 'page_custom',
      limit: 'limit_custom'
    }
  }
}

Response from backend

This package automatically handles the response from backend and convert it into an instance of a such Model.

Single object

If your backend responds with the following response…

// Note: the response data is the root element with no 'data' wrapper
{
  id: 1,
  firstname: 'John',
  lastname: 'Doe',
  age: 25
}

Then using find() and first() will work as expected and will hydrate the response into the User Model.

let user = await User.find(1)

// or

let user = await User.first()

// will work - an instance of User was created from response

user.makeBirthday()

However, if the backend sends a response like this…

// Note: the response is wrapped with 'data' attribute...
data: {
  {
    id: 1,
    firstname: 'John',
    lastname: 'Doe',
    age: 25
  }
}

…then the above would fail. If your backend wraps single objects with a data attribute too then you should use the fetch method of find (which is $find()) instead to automatically hydrate the Model with the response data:

let user = await User.$find(1)

// or

let user = await User.$first()

// will work, because an instance of User was created from response

user.makeBirthday()

This WILL NOT be converted into User model, because the main data is not the root element or it is not wrapped by data attribute.

user: {  
    id: 1,
    firstname: 'John',
    lastname: 'Doe',
    age: 25
}

Array of objects

An array of items from backend would be converted in the same way, ONLY if it responds in these formats:

let users = await User.get()
// works - array of object is the root element
[
  {
    id: 1,
    firstname: 'John',
    lastname: 'Doe',
    age: 25
  },
  {
    id: 2,
    firstname: 'Mary',
    lastname: 'Doe',
    age: 22
  }
]
// works - `data` exists in the root and contains the array of objects 
{
  data: [
    {
      id: 1,
      firstname: 'John',
      lastname: 'Doe',
      age: 25
      },
    {
      id: 2,
      firstname: 'Mary',
      lastname: 'Doe',
      age: 22
    }
  ],
  someField: '',
  anotherOne: '',  
}

// Normally you would handle the response like this

let response = User.get()
let users = response.data

// or like this

const { data } = User.get()
let users  = data

// but you can use the "fetch style request" with "$get()"

let users = await User.$get()

This WILL NOT be converted into an array of User model.

{
  users: [
    {
      id: 1,
      firstname: 'John',
      lastname: 'Doe',
      age: 25
      },
    {
      id: 2,
      firstname: 'Mary',
      lastname: 'Doe',
      age: 22
    }
  ],
  someField: '',
  anotherOne: '',  
}

Download Details:

Author: robsontenorio

GitHub: https://github.com/robsontenorio/vue-api-query

#vuejs #javascript #vue-js

What is GEEK

Buddha Community

Elegant and simple way to build requests for REST API
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

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

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

Chaz  Homenick

Chaz Homenick

1602725748

Why You Should Consider Low-Code Approach to Building a REST API

APIs have been around for decades – they allow different systems to talk to each other in a seamless, fast fashion – yet it’s been during the past decade that this technology has become a significant force.

So then why all the interest in APIs? We all know the usual stories – Uber, Airbnb, Apple Pay… the list goes on, and the reasons are plentiful. Today the question is, how? Perhaps you are looking to differentiate your business or want a first-mover advantage.  How can you execute quickly and at low cost/risk to try new market offerings?

An API provides several benefits to an organisation, but without a dedicated team of trained developers, it might seem like an implausible option. Developers are expensive, and it can take months to develop an API from the ground up. If you don’t fancy outsourcing or have the capability in house to build internal APIs, a low-code platform might just be the answer.

Before You Begin: Plan long-term, start small.

For a small one-page application, this might only be a day or two of talking with stakeholders and designing business logic. The purpose of this first step is to ensure that the API will cover all use cases and provides stakeholders with what they need. Refactoring an entire coding design due to missing business logic is not only frustrating for the development team but adds high cost and time to the API project.

During the planning and design stage, remember that running an API requires more infrastructure than just resources to execute endpoint logic. You need a database to store the data, an email system to send messages, storage for files, and security to handle authorisation and authentication. These services can be farmed out to cloud providers to expedite the API build process (e.g. AWS provides all these infrastructure components, but Microsoft Azure is an optional cloud provider with SendGrid as the email application.)

**Planning considerations: **An API “speaks” in JSON or XML, so the output provided to client applications should be decided. Should you choose to later create endpoints for public developer consumption, you could offer both for ease-of-use and fostering more adoption. Ensuring the API follows OpenAPI standards will encourage more adoption and attract more developers.

#api #rest-api #api-development #restful-api #low-code-platform #low-code #build-a-rest-api #low-code-approach