曾 俊

曾 俊

1677245718

Warp を使用して Rust で REST API を構築する方法

Rust で warp を使用して REST API を構築する方法を学びます。Rust と warp を使用して最初の REST API を作成します。Warp は、Rust で HTTP ベースの Web サービスを構築するための最小限で効率的な Web フレームワークです。 

Rust は多くの人々のお気に入りのプログラミング言語ですが、Rust のプロジェクトを見つけることはもちろん、Rust をしっかりと理解することさえ難しい場合があります。どの言語でも、毎日使用するものを作成することから始めるのが良い方法です。会社がマイクロサービスを運用している場合は、さらに簡単になります。Rust はそのようなサービスを置き換えるのに適していて、数日で書き直すことができます。

Rust を始めるときは、基礎を学ぶ必要があります。構文と基本概念に慣れたら、非同期 Rust について考え始めることができます。最近のほとんどの言語には、要求の送信やバックグラウンドでの応答の待機などの非同期タスクを処理する組み込みのランタイムがあります。

Rust では、自分に合った非同期ランタイムを選択する必要があります。ライブラリには通常、独自のランタイムがあります。大規模なプロジェクトで作業する場合、複数のランタイムを追加することは避けたほうがよいかもしれません。これは、単一の一貫したランタイムを選択することで、アプリケーション アーキテクチャを簡素化し、アプリケーションの複雑さと互換性の問題のリスクを軽減できるためです。

Tokio は、非同期タスクを処理できる実稼働環境で最も使用され、実績のあるランタイムであるため、将来の雇用主が既に使用している可能性が高くなります。したがって、API を作成するために既に Tokio が組み込まれているライブラリを選択する必要がある場合があるため、選択肢はいくらか制限されます。このチュートリアルでは、 warpを使用します。これまでのプログラミング経験によっては、理解するのに数日かかる場合があります。しかし、warp を理解すれば、API を構築するための非常に洗練されたツールになる可能性があります。

目次:

  • ワープとは?
  • プロジェクトの設定
  • REST API の構築
    • ローカル ストレージの作成
    • POSTリストに項目を追加する
    • GET食料品リストを作る
    • UPDATEDELETE
  • テストカールを理解する
  • Rust でワープを使用する理由

ワープとは?

Warp は、Rust で HTTP ベースの Web サービスを構築するための最小限で効率的な Web フレームワークです。セキュリティ、パフォーマンス、および安定性に重点を置いて、HTTP サーバーを構築するための高レベル API を提供します。Warp には、HTTP/1 および HTTP/2 のサポート、TLS 暗号化、非同期プログラミング、ロギング、レート制限、およびルーティング タスク用の一般的なミドルウェアなどの組み込み機能も含まれています。warp はHyperのスーパーセットに似ているため、その機能の多くは Hyper から借用されています。

プロジェクトの設定

このチュートリアルを進めるには、次のライブラリをインストールする必要があります。

  • API を作成するためのワープ
  • 非同期サーバーを実行するTokio
  • 着信 JSON のシリアライズを支援する Serde
  • ReadWriteLockローカルストレージ用にparking_lotを作成します

まず、貨物で新しいプロジェクトを作成します。

貨物新しいきちんとした api --bin

Cargo.tomlコードベース全体で使用できるように、warp を含めました。


[dependencies]
warp = "0.2"
parking_lot = "0.10.0"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "0.2", features = ["macros"] }

最初のテストでは、単純な「Hello, World!」を作成します。以下に示すようにmain.rs
 

use warp::Filter;

#[tokio::main]
async fn main() {
    // GET /hello/warp => 200 OK with body "Hello, warp!"
    let hello = warp::path!("hello" / String)
        .map(|name| format!("Hello, {}!", name));

    warp::serve(hello)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

Filtersリクエストを解析し、作成したルートと照合する方法です。したがって、 経由でサーバーを起動しcargo run、ブラウザを にポイントするとlocalhost:3030/hello/WHATEVER、warp はこのリクエストをフィルタを介して送信し、トリガーされた最初のリクエストを実行します。

では、let hello = …新しいパスを作成しました。基本的には、パス/helloと文字列を含むすべてのリクエストがこのメソッドによって処理されるということです。したがって、 を返しますHello, WHATEVER
ブラウザを に向けるとlocalhost:3030/hello/new/WHATEVER、 のフィルタがないため、404 が返されます/hello/new + String

REST API の構築

Let’s build a real API to demonstrate these concepts. A good model is an API for a grocery list. We want to be able to add items to the list, update the quantity, delete items, and view the whole list. Therefore, we need four different routes with the HTTP methods GET, DELETE, PUT, and POST.
With so many different routes, is it wise to create methods for each instead of handling them all in main.rs?

Creating local storage

In addition to routes, we need to store a state in a file or local variable. In an async environment, we have to make sure only one method can access the store at a time so there are no inconsistencies between threads.

In Rust, we have Arc, so the compiler knows when to drop a value and a read and write lock (RwLock). That way, no two methods on different threads are writing to the same memory.
Your store implementation should look like this:

use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;

type Items = HashMap<String, i32>;

#[derive(Debug, Deserialize, Serialize, Clone)]
struct Item {
    name: String,
    quantity: i32,
}

#[derive(Clone)]
struct Store {
  grocery_list: Arc<RwLock<Items>>
}

impl Store {
    fn new() -> Self {
        Store {
            grocery_list: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

POSTing an item to the list

Now, we can add our first route. To add items to the list, make an HTTP POST request to a path. Our method has to return a proper HTTP code so the caller knows whether their call was successful. Warp offers basic types via its own http library, which we need to include as well. Add it like so:

use warp::{http, Filter};

The method for the POST request looks like this:

async fn add_grocery_list_item(
    item: Item,
    store: Store
    ) -> Result<impl warp::Reply, warp::Rejection> {
        let r = store.grocery_list.read();
        Ok(warp::reply::json(&*r))
}

reply with statuswarp フレームワークには、テキストと一般的な HTTP ステータスを追加できるオプションが用意されているため、発信者はリクエストが成功したかどうか、または再試行する必要があるかどうかを知ることができます。次に、新しいルートを追加し、作成したばかりのメソッドを呼び出します。これには JSON が期待できるため、 HTTP 要求からを抽出するための小さなjson_bodyヘルパー関数を作成する必要があります。Itembody

さらに、ストアを複製して を作成することにより、ストアを各メソッドに渡す必要があります。これは、作成中warp filterに で呼び出します。.and()warp path

fn json_body() -> impl Filter<Extract = (Item,), Error = warp::Rejection> + Clone {
    // When accepting a body, we want a JSON body
    // (and to reject huge payloads)...
    warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}

#[tokio::main]
async fn main() {
    let store = Store::new();
    let store_filter = warp::any().map(move || store.clone());

    let add_items = warp::post()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(json_body())
        .and(store_filter.clone())
        .and_then(add_grocery_list_item);

    warp::serve(add_items)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

またはPostmanなどのアプリケーションをPOST介して呼び出しをテストできます。これは、HTTP 要求を行うためのスタンドアロン アプリケーションになりました。経由でサーバーを起動し、別のターミナル ウィンドウまたはタブを開いて、次のコマンドを実行します。curlcargo runcurl

curl --location --request POST 'localhost:3030/v1/groceries' \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
        "name": "apple",
        "quantity": 3
}'

メソッドで定義されているテキスト応答と HTTP コードを取得する必要があります。

GET食料品リストを作る

これで、アイテムのリストを買い物リストに投稿できますが、まだそれらを取得することはできません。リクエスト用に別のルートを作成する必要がありますGET。メイン関数は、この新しいルートを追加します。この新しいルートでは、JSON を解析する必要はありません。コードは次のとおりです。

#[tokio::main]
async fn main() {
    let store = Store::new();
    let store_filter = warp::any().map(move || store.clone());

    let add_items = warp::post()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(json_body())
        .and(store_filter.clone())
        .and_then(add_grocery_list_item);

    let get_items = warp::get()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(store_filter.clone())
        .and_then(get_grocery_list);


    let routes = add_items.or(get_items);

    warp::serve(routes)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

の背後にあるデータ構造を調べると、非同期 Rust の味がわかりますArc.read()メソッドを使用してデータにアクセスし、逆参照する必要があります。関数の外観は次のとおりです。

async fn get_grocery_list(
    store: Store
    ) -> Result<impl warp::Reply, warp::Rejection> {
         let result = store.grocery_list.read();
        Ok(warp::reply::json(&*result))
}

次に、 の変数を作成しますstore.grocery_list.read()。これを と呼びますresult。新しいものを返すことに注意してください&*result;ね。はい、オブジェクトを に&*result逆参照し、返された関数への参照として渡されます。RwLockReadGuardresult&HashMapwarp::reply::json

UPDATEとDELETE

不足している最後の 2 つのメソッドは とUPDATEですDELETE。の場合はDELETE、ほとんどコピーできますadd_grocery_list_itemが、代わりに.insert()エントリ.remove()をコピーします。

特殊なケースはUPDATE. ここで Rust実装も同様にHashMap使用しますが、キーが存在しない場合、新しいエントリを作成する代わりに値を更新します。したがって、メソッドの名前を変更して、および に対して.insert()呼び出すだけです。POSTPUT

メソッドについてはDELETE、アイテムの名前だけを渡す必要があるため、新しい構造体を作成し、parse_json()新しい型に別のメソッドを追加します。最初の解析メソッドの名前を変更し、別の解析メソッドを追加します。

add_grocery_list_itemメソッドの名前を変更して呼び出すだけで、 aおよびupdate_grocery_listに対して呼び出すことができます。完全なコードは次のようになります。warp::post()warp::put()

use warp::{http, Filter};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use serde::{Serialize, Deserialize};

type Items = HashMap<String, i32>;

#[derive(Debug, Deserialize, Serialize, Clone)]
struct Id {
    name: String,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
struct Item {
    name: String,
    quantity: i32,
}

#[derive(Clone)]
struct Store {
  grocery_list: Arc<RwLock<Items>>
}

impl Store {
    fn new() -> Self {
        Store {
            grocery_list: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

async fn update_grocery_list(
    item: Item,
    store: Store
    ) -> Result<impl warp::Reply, warp::Rejection> {
        store.grocery_list.write().insert(item.name, item.quantity);


        Ok(warp::reply::with_status(
            "Added items to the grocery list",
            http::StatusCode::CREATED,
        ))
}

async fn delete_grocery_list_item(
    id: Id,
    store: Store
    ) -> Result<impl warp::Reply, warp::Rejection> {
        store.grocery_list.write().remove(&id.name);


        Ok(warp::reply::with_status(
            "Removed item from grocery list",
            http::StatusCode::OK,
        ))
}

async fn get_grocery_list(
    store: Store
    ) -> Result<impl warp::Reply, warp::Rejection> {
        let r = store.grocery_list.read();
        Ok(warp::reply::json(&*r))
}

fn delete_json() -> impl Filter<Extract = (Id,), Error = warp::Rejection> + Clone {
    // When accepting a body, we want a JSON body
    // (and to reject huge payloads)...
    warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}

fn post_json() -> impl Filter<Extract = (Item,), Error = warp::Rejection> + Clone {
    // When accepting a body, we want a JSON body
    // (and to reject huge payloads)...
    warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}

#[tokio::main]
async fn main() {
    let store = Store::new();
    let store_filter = warp::any().map(move || store.clone());

    let add_items = warp::post()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(post_json())
        .and(store_filter.clone())
        .and_then(update_grocery_list);

    let get_items = warp::get()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(store_filter.clone())
        .and_then(get_grocery_list);

    let delete_item = warp::delete()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(delete_json())
        .and(store_filter.clone())
        .and_then(delete_grocery_list_item);


    let update_item = warp::put()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(post_json())
        .and(store_filter.clone())
        .and_then(update_grocery_list);



    let routes = add_items.or(get_items).or(delete_item).or(update_item);

    warp::serve(routes)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

テストカールを理解する

コードを更新したら、サーバーを再起動しcargo run、これらのカールを使用してアイテムを投稿、更新、取得、および削除します。

POST

curl --location --request POST 'localhost:3030/v1/groceries' \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
        "name": "apple",
        "quantity": 3
}'

UPDATE

curl --location --request PUT 'localhost:3030/v1/groceries' \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
        "name": "apple",
        "quantity": 5
}'

GET

curl --location --request GET 'localhost:3030/v1/groceries' \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain'

DELETE

curl --location --request DELETE 'localhost:3030/v1/groceries' \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
        "name": "apple"
}'

今説明した手順を要約すると、次のようになります。

  • 各アイテムの ID を作成して、次の方法で更新および削除できるようにします。/v1/groceries/{id}
  • 404 ルートを追加する
  • 不正な形式の JSON のエラー処理を追加する
  • ルートごとに返信メッセージを調整する
  • curls を使用してルートごとにテストを追加する

Rust でワープを使用する理由

Rust で API を構築する場合、いくつかのライブラリ オプションがあります。ただし、プロジェクトの特定の要件が選択の指針となります。warp を使用する場合、Rust プロジェクトで warp を使用する利点がいくつかあります。

  1. パフォーマンス: warp は、非同期処理と、自動 HTTP キープアライブや接続プーリングなどのパフォーマンス最適化機能に重点を置いて、高速かつ効率的に設計されています。
  2. セキュリティ: warp はセキュリティに重点を置いており、TLS 暗号化の組み込みサポートなどの機能を使用して、データがネットワーク上で安全に送信されるようにします。
  3. シンプルさ: warp は、使いやすく、強力でカスタマイズ可能な高レベル API を提供します。これにより、HTTP サーバーの構築を簡単に開始でき、必要に応じて機能を追加してアプリケーションを簡単に拡張できます。
  4. 堅牢性: warp は、エラー処理とレポートに重点を置いて、安定して信頼できるように設計されています。
  5. スケーラビリティ: warp はスケーラブルになるように設計されており、HTTP/1 と HTTP/2 をサポートし、リソースを効率的に使用できるため、高性能でスケーラブルな Web アプリケーションを構築するための優れた選択肢となっています。

最終的な考え

Warp は、Rust で Web API を構築するための興味深いツールです。コードは完璧にはほど遠いですが、サンプル コードは、warp で何ができるかについての氷山の一角を示しています。私たちはそれを延長することができます。すでに作成したものに基づいたフィードバックをお待ちしています。

追加できるもの:

  • エラー処理
  • 単体テスト
  • 統合された JSON 応答

Rust と warp を使用して最初の REST API を作成するのがいかに簡単か、また Rust 型システムによって、処理しているデータと使用可能なメソッドがどのように明確になるかがわかります。スキルを磨き、コードを最適化するのはあなた次第です。完全なソース コードはGitHubにあります。自由に複製して実験し、改善してください。

ソース: https://blog.logrocket.com

#rust #api

What is GEEK

Buddha Community

Warp を使用して Rust で 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

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