Developer Preview: Ruby SDK code generation using Smithy

海外精选
海外精选的内容汇集了全球优质的亚马逊云科技相关技术内容。同时,内容中提到的“AWS” 是 “Amazon Web Services” 的缩写,在此网站不作为商标展示。
0
0
{"value":"### **What is this?**\n\nThe AWS SDK For Ruby team is happy to announce the developer preview of [smithy-ruby](https://github.com/awslabs/smithy-ruby), a toolchain that can be used to code generate a “[white label](https://en.wikipedia.org/wiki/White-label_product)” Ruby SDK for your service API using Smithy modeling. An upcoming future version of the AWS SDK For Ruby will use Smithy code generation.\n\n### **What is Smithy?**\n\nSmithy is an interface definition language and set of tools that allows developers to build clients and servers in multiple languages. Smithy models define a service as a collection of resources, operations, and shapes. A Smithy model enables API providers to generate clients and servers in various programming languages, API documentation, test automation, and example code. For more information about Smithy, see the [Smithy documentation](https://awslabs.github.io/smithy/index.html).\n\n### **What’s included in the Ruby SDK**\n\n![image.png](https://dev-media.amazoncloud.cn/acb7a0eb641c4553841df03b966483bf_image.png)\n\n**Components of a code generated Ruby SDK**\n\nA code generated Ruby SDK using Smithy will have generic components and protocol specific components. These components are (in no particular order):\n\n- **Validators (private)** – A set of classes that validate Ruby input types against the Smithy model.\n- **Builders (private, protocol)** – A set of classes that build a protocol specific request using input (i.e. JSON over HTTP).\n- **Stubs (private, protocol)** – A set of classes that build a protocol specific response using stub data, used for testing.\n- **Parsers (private, protocol)** – A set of classes that parse a protocol specific response into data structures (i.e. XML over HTTP).\n- **Types (public)** – A set of classes that represent structure shapes (Plain Old Ruby Objects).\n- **Errors (public, protocol)** – A set of classes that represent error shapes and protocol specific error classes.\n- **Params (private)** – A set of modules that convert hash-y input to rigid input types used by the Client operations.\n- **Paginators (public)** – A set of classes used for traversing paginated operations automatically.\n- **Waiters (public)** – A set of classes used to wait until an operation reaches a desired state before resuming control back to the client.\n- **Client (public)** – A class that ties everything together; it is the public interface to the service API. The client is responsible for constructing requests and returning responses using middleware.\n\nFor more information about the components, please see the [smithy-ruby wiki](https://github.com/awslabs/smithy-ruby/wiki).\n\n### **Middleware**\n\nMiddleware are classes that sit between the client and the server, providing a way to modify the request-response cycle. At minimum, middleware is used to build a request, send a request, and parse a response. Middleware is organized in a stack and are responsible for calling the next middleware.\n\n![image.png](https://dev-media.amazoncloud.cn/e91a387feab74073887d46e1068be5e6_image.png)\n\n**Middleware stack**\n\nIn the client, each API operation will have a method that is responsible for creating its own middleware stack and handling the request and response cycle. Seahorse will ship with 6 default middleware. Each middleware will have access to the request, response, and context.\n\nIn detail, the middleware components are:\n\n- **Validate** – Validates input using the Validator classes if configured to do so. (Optional – client configuration)\n- **Build** – Builds a protocol specific request (i.e. JSON over HTTP) using the Builder classes and input.\n- **HostPrefix** – Modifies the endpoint with a host prefix if configured to do so. (Optional – Smithy trait)\n- **Send** – Sends the request using a protocol specific client (i.e. HTTP client). The middleware may return responses using the Stubs classes if configured to do so.\n- **Parse** – Parses a protocol specific response (i.e. XML over HTTP) using the Parser classes and the raw service response.\n- **Retry** – Retries a request for networking errors and any responses with retry-able or throttling errors.\n\n\nProtocol implementations may also insert their own code generated middleware. Middleware may also be added at runtime to a Client class or Client instance, and to individual operation calls.\n\n### **Rails JSON Protocol**\n\nA Smithy built Ruby SDK needs a protocol implementation to fully function, much like a car needs an engine. As part of this developer preview, we will be including a protocol implementation that we are calling “[Rails JSON](https://github.com/awslabs/smithy-ruby/wiki/Rails-JSON-Protocol)”. With the Rails JSON protocol definition, a Smithy model can be used to code generate a Ruby SDK that communicates directly with a Rails API over JSON. Neat!\n\nAs a demo, the following sections will detail how to setup a Rails service and generate an SDK that can communicate with it.\n\n#### **Setup Rails API Service**\n\nBefore we can create an SDK, we need a service for it to communicate to. Let’s first create a new Rails API service with: ```rails new --api sample-service```.\n\nNext, echoing [rails documentation](https://guides.rubyonrails.org/command_line.html), let’s create a High Score model with ```rails generate scaffold HighScore game:string score:integer``` and run ```rake db:migrate```.\n\nIn ```models/high_score.rb```, add a length validation to the game’s name by adding: ```validates :game, length: { minimum: 2 }.``` This validation will be used later.\n\nNow it’s time to start our rails app with ```rails s``` and verify it’s running on an endpoint such as ```http://127.0.0.1:3000```; we will need this endpoint for later.\n\nIf you aren’t able to generate a Rails app, don’t worry, a [copy of this sample Rails service](https://github.com/awslabs/smithy-ruby/tree/4cba34e43867a84272be12812d66cc032f92a966/sample-service) lives in smithy-ruby for now.\n\n#### **Add the Smithy model**\n\nTo generate the SDK, we need the Smithy model that describes the Rails service we just defined. I’ve conveniently defined this in smithy-ruby in [high-score-service.smithy](https://github.com/awslabs/smithy-ruby/blob/4cba34e43867a84272be12812d66cc032f92a966/codegen/smithy-ruby-rails-codegen-test/model/high-score-service.smithy). The model tells smithy-ruby to code generate shapes and a client API for the High Score service and to use Rails’ JSON protocol.\n\nLet’s break down some of the important parts.\n\nThe first section tells Smithy to create the HighScoreService using the Rails JSON protocol and define its resources and operations. The resource has an identifier (Rails defaults to id), which is used to look up the High Score. The resource has all of the basic Rails CRUD operations: get, create, update, delete, and list\n\nRuby\n```\n@railsJson\n@title(\"High Score Sample Rails Service\")\nservice HighScoreService {\n version: \"2021-02-15\",\n resources: [HighScore],\n}\n\n/// Rails default scaffold operations\nresource HighScore {\n identifiers: { id: String },\n read: GetHighScore,\n create: CreateHighScore,\n update: UpdateHighScore,\n delete: DeleteHighScore,\n list: ListHighScores\n}\n```\nThe next sections define the service shapes. HighScoreAttributes is a shape that returns all of the properties of a High Score. HighScoreParams includes all of the properties that a High Score will need. The @length validation of >2 characters is applied to game.\n\nRuby\n\n```\n/// Modeled attributes for a High Score\nstructure HighScoreAttributes {\n /// The high score id\n id: String,\n /// The game for the high score\n game: String,\n /// The high score for the game\n score: Integer,\n // The time the high score was created at\n createdAt: Timestamp,\n // The time the high score was updated at\n updatedAt: Timestamp\n}\n\n/// Permitted params for a High Score\nstructure HighScoreParams {\n /// The game for the high score\n @length(min: 2)\n game: String,\n /// The high score for the game\n score: Integer\n}\n```\nNext are the operation shapes. The @http trait is applied to each operation with the expected Rails path.\n\nRuby\n\n```\n/// Get a high score\n@http(method: \"GET\", uri: \"/high_scores/{id}\")\n@readonly\noperation GetHighScore {\n input: GetHighScoreInput,\n output: GetHighScoreOutput\n}\n\n/// Input structure for GetHighScore\nstructure GetHighScoreInput {\n /// The high score id\n @required\n @httpLabel\n id: String\n}\n\n/// Output structure for GetHighScore\nstructure GetHighScoreOutput {\n /// The high score attributes\n @httpPayload\n highScore: HighScoreAttributes\n}\n\n/// Create a new high score\n@http(method: \"POST\", uri: \"/high_scores\", code: 201)\noperation CreateHighScore {\n input: CreateHighScoreInput,\n output: CreateHighScoreOutput,\n errors: [UnprocessableEntityError]\n}\n\n/// Input structure for CreateHighScore\nstructure CreateHighScoreInput {\n /// The high score params\n @required\n highScore: HighScoreParams\n}\n\n/// Output structure for CreateHighScore\nstructure CreateHighScoreOutput {\n /// The high score attributes\n @httpPayload\n highScore: HighScoreAttributes,\n\n /// The location of the high score\n @httpHeader(\"Location\")\n location: String\n}\n\n/// Update a high score\n@http(method: \"PUT\", uri: \"/high_scores/{id}\")\n@idempotent\noperation UpdateHighScore {\n input: UpdateHighScoreInput,\n output: UpdateHighScoreOutput,\n errors: [UnprocessableEntityError]\n}\n\n/// Input structure for UpdateHighScore\nstructure UpdateHighScoreInput {\n /// The high score id\n @required\n @httpLabel\n id: String,\n\n /// The high score params\n highScore: HighScoreParams\n}\n\n/// Output structure for UpdateHighScore\nstructure UpdateHighScoreOutput {\n /// The high score attributes\n @httpPayload\n highScore: HighScoreAttributes\n}\n\n/// Delete a high score\n@http(method: \"DELETE\", uri: \"/high_scores/{id}\")\n@idempotent\noperation DeleteHighScore {\n input: DeleteHighScoreInput,\n output: DeleteHighScoreOutput\n}\n\n/// Input structure for DeleteHighScore\nstructure DeleteHighScoreInput {\n /// The high score id\n @required\n @httpLabel\n id: String\n}\n\n/// Output structure for DeleteHighScore\nstructure DeleteHighScoreOutput {}\n\n/// List all high scores\n@http(method: \"GET\", uri: \"/high_scores\")\n@readonly\noperation ListHighScores {\n output: ListHighScoresOutput\n}\n\n/// Output structure for ListHighScores\nstructure ListHighScoresOutput {\n /// A list of high scores\n @httpPayload\n highScores: HighScores\n}\n\nlist HighScores {\n member: HighScoreAttributes\n}\n```\n\n#### **Generate the SDK**\n\nWith the model and a Rails service, it’s now time to generate the SDK. Smithy code generation and integration is only available in Java environments. Fortunately, for this demo, the High Score Service SDK has already been generated and committed to the smithy-ruby repo. Download it [from here](https://github.com/awslabs/smithy-ruby/tree/4cba34e43867a84272be12812d66cc032f92a966/codegen/projections/high_score_service) if you are following along!\n\nIf you’d like to generate it yourself, or generate your own Smithy model, you can follow the [README instructions](https://github.com/awslabs/smithy-ruby/blob/main/README.md#generating-an-sdk-for-a-rails-json-api) that detail how to use smithy-ruby in your Gradle project.\n\n#### **Use the SDK**\n\nNow we have a Rails service and an SDK. Start up ```irb``` with ```irb -I high_score_service/lib``` and try it out!\n\nRuby\n\n```\nrequire 'high_score_service'\n\n# Create an instance of HighScoreService's Client.\n# This is similar to the AWS SDK Clients.\n# Here we use the endpoint of the Rails service.\nclient = HighScoreService::Client.new(endpoint: 'http://127.0.0.1:3000')\n\n# List all high scores\nclient.list_high_scores\n# => #<struct HighScoreService::Types::ListHighScoresOutput high_scores=[]>\n\n# Try to create a high score\n# Should raise an UnprocessableEntityError, let's find out why\n begin\n client.create_high_score(high_score: { score: 9001, game: 'X' })\nrescue => e\n puts e.data\n # => #<struct HighScoreService::Types::UnprocessableEntityError errors={\"game\"=>[\"is too short (minimum is 2 characters)\"]}>\nend\n\n# Actually create a high score\nclient.create_high_score(high_score: { score: 9001, game: 'Frogger' })\n# => #<struct HighScoreService::Types::CreateHighScoreOutput\n\n# List high scores again\nresp = client.get_high_score(id: '1')\nresp.high_score\n# => #<struct HighScoreService::Types::HighScoreAttributes id=1, game=\"Frogger\", score=9001 ... >\n```\nAs an exercise, try out the ```delete_high_score``` and ```update_high_score``` operations.\n\n### **Future Plans**\nLooking forward, smithy-ruby will be used to generate the new service client versions (gem version 2, core version 4) of AWS SDK For Ruby.\n\nWe’d like to explore more Smithy Ruby and Rails API use cases. Perhaps a Smithy model can be parsed and translated into a set of ```rails new``` and ```rails generate``` commands; going further, perhaps a “server-side SDK” can be a pluggable Rails engine that handles building and parsing of concrete types and protocols.\n\n### **Feedback**\n\nIf you have any questions, comments, concerns, ideas, or other feedback, please create an issue or discussion in the [smithy-ruby repository](https://github.com/awslabs/smithy-ruby). We welcome any SDK design feedback and improvements, and we especially welcome any community contributions.\n\nThanks for reading!\n\n-Matt","render":"<h3><a id=\"What_is_this_0\"></a><strong>What is this?</strong></h3>\n<p>The AWS SDK For Ruby team is happy to announce the developer preview of <a href=\"https://github.com/awslabs/smithy-ruby\" target=\"_blank\">smithy-ruby</a>, a toolchain that can be used to code generate a “<a href=\"https://en.wikipedia.org/wiki/White-label_product\" target=\"_blank\">white label</a>” Ruby SDK for your service API using Smithy modeling. An upcoming future version of the AWS SDK For Ruby will use Smithy code generation.</p>\n<h3><a id=\"What_is_Smithy_4\"></a><strong>What is Smithy?</strong></h3>\n<p>Smithy is an interface definition language and set of tools that allows developers to build clients and servers in multiple languages. Smithy models define a service as a collection of resources, operations, and shapes. A Smithy model enables API providers to generate clients and servers in various programming languages, API documentation, test automation, and example code. For more information about Smithy, see the <a href=\"https://awslabs.github.io/smithy/index.html\" target=\"_blank\">Smithy documentation</a>.</p>\n<h3><a id=\"Whats_included_in_the_Ruby_SDK_8\"></a><strong>What’s included in the Ruby SDK</strong></h3>\n<p><img src=\"https://dev-media.amazoncloud.cn/acb7a0eb641c4553841df03b966483bf_image.png\" alt=\"image.png\" /></p>\n<p><strong>Components of a code generated Ruby SDK</strong></p>\n<p>A code generated Ruby SDK using Smithy will have generic components and protocol specific components. These components are (in no particular order):</p>\n<ul>\n<li><strong>Validators (private)</strong> – A set of classes that validate Ruby input types against the Smithy model.</li>\n<li><strong>Builders (private, protocol)</strong> – A set of classes that build a protocol specific request using input (i.e. JSON over HTTP).</li>\n<li><strong>Stubs (private, protocol)</strong> – A set of classes that build a protocol specific response using stub data, used for testing.</li>\n<li><strong>Parsers (private, protocol)</strong> – A set of classes that parse a protocol specific response into data structures (i.e. XML over HTTP).</li>\n<li><strong>Types (public)</strong> – A set of classes that represent structure shapes (Plain Old Ruby Objects).</li>\n<li><strong>Errors (public, protocol)</strong> – A set of classes that represent error shapes and protocol specific error classes.</li>\n<li><strong>Params (private)</strong> – A set of modules that convert hash-y input to rigid input types used by the Client operations.</li>\n<li><strong>Paginators (public)</strong> – A set of classes used for traversing paginated operations automatically.</li>\n<li><strong>Waiters (public)</strong> – A set of classes used to wait until an operation reaches a desired state before resuming control back to the client.</li>\n<li><strong>Client (public)</strong> – A class that ties everything together; it is the public interface to the service API. The client is responsible for constructing requests and returning responses using middleware.</li>\n</ul>\n<p>For more information about the components, please see the <a href=\"https://github.com/awslabs/smithy-ruby/wiki\" target=\"_blank\">smithy-ruby wiki</a>.</p>\n<h3><a id=\"Middleware_29\"></a><strong>Middleware</strong></h3>\n<p>Middleware are classes that sit between the client and the server, providing a way to modify the request-response cycle. At minimum, middleware is used to build a request, send a request, and parse a response. Middleware is organized in a stack and are responsible for calling the next middleware.</p>\n<p><img src=\"https://dev-media.amazoncloud.cn/e91a387feab74073887d46e1068be5e6_image.png\" alt=\"image.png\" /></p>\n<p><strong>Middleware stack</strong></p>\n<p>In the client, each API operation will have a method that is responsible for creating its own middleware stack and handling the request and response cycle. Seahorse will ship with 6 default middleware. Each middleware will have access to the request, response, and context.</p>\n<p>In detail, the middleware components are:</p>\n<ul>\n<li><strong>Validate</strong> – Validates input using the Validator classes if configured to do so. (Optional – client configuration)</li>\n<li><strong>Build</strong> – Builds a protocol specific request (i.e. JSON over HTTP) using the Builder classes and input.</li>\n<li><strong>HostPrefix</strong> – Modifies the endpoint with a host prefix if configured to do so. (Optional – Smithy trait)</li>\n<li><strong>Send</strong> – Sends the request using a protocol specific client (i.e. HTTP client). The middleware may return responses using the Stubs classes if configured to do so.</li>\n<li><strong>Parse</strong> – Parses a protocol specific response (i.e. XML over HTTP) using the Parser classes and the raw service response.</li>\n<li><strong>Retry</strong> – Retries a request for networking errors and any responses with retry-able or throttling errors.</li>\n</ul>\n<p>Protocol implementations may also insert their own code generated middleware. Middleware may also be added at runtime to a Client class or Client instance, and to individual operation calls.</p>\n<h3><a id=\"Rails_JSON_Protocol_51\"></a><strong>Rails JSON Protocol</strong></h3>\n<p>A Smithy built Ruby SDK needs a protocol implementation to fully function, much like a car needs an engine. As part of this developer preview, we will be including a protocol implementation that we are calling “<a href=\"https://github.com/awslabs/smithy-ruby/wiki/Rails-JSON-Protocol\" target=\"_blank\">Rails JSON</a>”. With the Rails JSON protocol definition, a Smithy model can be used to code generate a Ruby SDK that communicates directly with a Rails API over JSON. Neat!</p>\n<p>As a demo, the following sections will detail how to setup a Rails service and generate an SDK that can communicate with it.</p>\n<h4><a id=\"Setup_Rails_API_Service_57\"></a><strong>Setup Rails API Service</strong></h4>\n<p>Before we can create an SDK, we need a service for it to communicate to. Let’s first create a new Rails API service with: <code>rails new --api sample-service</code>.</p>\n<p>Next, echoing <a href=\"https://guides.rubyonrails.org/command_line.html\" target=\"_blank\">rails documentation</a>, let’s create a High Score model with <code>rails generate scaffold HighScore game:string score:integer</code> and run <code>rake db:migrate</code>.</p>\n<p>In <code>models/high_score.rb</code>, add a length validation to the game’s name by adding: <code>validates :game, length: { minimum: 2 }.</code> This validation will be used later.</p>\n<p>Now it’s time to start our rails app with <code>rails s</code> and verify it’s running on an endpoint such as <code>http://127.0.0.1:3000</code>; we will need this endpoint for later.</p>\n<p>If you aren’t able to generate a Rails app, don’t worry, a <a href=\"https://github.com/awslabs/smithy-ruby/tree/4cba34e43867a84272be12812d66cc032f92a966/sample-service\" target=\"_blank\">copy of this sample Rails service</a> lives in smithy-ruby for now.</p>\n<h4><a id=\"Add_the_Smithy_model_69\"></a><strong>Add the Smithy model</strong></h4>\n<p>To generate the SDK, we need the Smithy model that describes the Rails service we just defined. I’ve conveniently defined this in smithy-ruby in <a href=\"https://github.com/awslabs/smithy-ruby/blob/4cba34e43867a84272be12812d66cc032f92a966/codegen/smithy-ruby-rails-codegen-test/model/high-score-service.smithy\" target=\"_blank\">high-score-service.smithy</a>. The model tells smithy-ruby to code generate shapes and a client API for the High Score service and to use Rails’ JSON protocol.</p>\n<p>Let’s break down some of the important parts.</p>\n<p>The first section tells Smithy to create the HighScoreService using the Rails JSON protocol and define its resources and operations. The resource has an identifier (Rails defaults to id), which is used to look up the High Score. The resource has all of the basic Rails CRUD operations: get, create, update, delete, and list</p>\n<p>Ruby</p>\n<pre><code class=\"lang-\">@railsJson\n@title(&quot;High Score Sample Rails Service&quot;)\nservice HighScoreService {\n version: &quot;2021-02-15&quot;,\n resources: [HighScore],\n}\n\n/// Rails default scaffold operations\nresource HighScore {\n identifiers: { id: String },\n read: GetHighScore,\n create: CreateHighScore,\n update: UpdateHighScore,\n delete: DeleteHighScore,\n list: ListHighScores\n}\n</code></pre>\n<p>The next sections define the service shapes. HighScoreAttributes is a shape that returns all of the properties of a High Score. HighScoreParams includes all of the properties that a High Score will need. The @length validation of &gt;2 characters is applied to game.</p>\n<p>Ruby</p>\n<pre><code class=\"lang-\">/// Modeled attributes for a High Score\nstructure HighScoreAttributes {\n /// The high score id\n id: String,\n /// The game for the high score\n game: String,\n /// The high score for the game\n score: Integer,\n // The time the high score was created at\n createdAt: Timestamp,\n // The time the high score was updated at\n updatedAt: Timestamp\n}\n\n/// Permitted params for a High Score\nstructure HighScoreParams {\n /// The game for the high score\n @length(min: 2)\n game: String,\n /// The high score for the game\n score: Integer\n}\n</code></pre>\n<p>Next are the operation shapes. The @http trait is applied to each operation with the expected Rails path.</p>\n<p>Ruby</p>\n<pre><code class=\"lang-\">/// Get a high score\n@http(method: &quot;GET&quot;, uri: &quot;/high_scores/{id}&quot;)\n@readonly\noperation GetHighScore {\n input: GetHighScoreInput,\n output: GetHighScoreOutput\n}\n\n/// Input structure for GetHighScore\nstructure GetHighScoreInput {\n /// The high score id\n @required\n @httpLabel\n id: String\n}\n\n/// Output structure for GetHighScore\nstructure GetHighScoreOutput {\n /// The high score attributes\n @httpPayload\n highScore: HighScoreAttributes\n}\n\n/// Create a new high score\n@http(method: &quot;POST&quot;, uri: &quot;/high_scores&quot;, code: 201)\noperation CreateHighScore {\n input: CreateHighScoreInput,\n output: CreateHighScoreOutput,\n errors: [UnprocessableEntityError]\n}\n\n/// Input structure for CreateHighScore\nstructure CreateHighScoreInput {\n /// The high score params\n @required\n highScore: HighScoreParams\n}\n\n/// Output structure for CreateHighScore\nstructure CreateHighScoreOutput {\n /// The high score attributes\n @httpPayload\n highScore: HighScoreAttributes,\n\n /// The location of the high score\n @httpHeader(&quot;Location&quot;)\n location: String\n}\n\n/// Update a high score\n@http(method: &quot;PUT&quot;, uri: &quot;/high_scores/{id}&quot;)\n@idempotent\noperation UpdateHighScore {\n input: UpdateHighScoreInput,\n output: UpdateHighScoreOutput,\n errors: [UnprocessableEntityError]\n}\n\n/// Input structure for UpdateHighScore\nstructure UpdateHighScoreInput {\n /// The high score id\n @required\n @httpLabel\n id: String,\n\n /// The high score params\n highScore: HighScoreParams\n}\n\n/// Output structure for UpdateHighScore\nstructure UpdateHighScoreOutput {\n /// The high score attributes\n @httpPayload\n highScore: HighScoreAttributes\n}\n\n/// Delete a high score\n@http(method: &quot;DELETE&quot;, uri: &quot;/high_scores/{id}&quot;)\n@idempotent\noperation DeleteHighScore {\n input: DeleteHighScoreInput,\n output: DeleteHighScoreOutput\n}\n\n/// Input structure for DeleteHighScore\nstructure DeleteHighScoreInput {\n /// The high score id\n @required\n @httpLabel\n id: String\n}\n\n/// Output structure for DeleteHighScore\nstructure DeleteHighScoreOutput {}\n\n/// List all high scores\n@http(method: &quot;GET&quot;, uri: &quot;/high_scores&quot;)\n@readonly\noperation ListHighScores {\n output: ListHighScoresOutput\n}\n\n/// Output structure for ListHighScores\nstructure ListHighScoresOutput {\n /// A list of high scores\n @httpPayload\n highScores: HighScores\n}\n\nlist HighScores {\n member: HighScoreAttributes\n}\n</code></pre>\n<h4><a id=\"Generate_the_SDK_243\"></a><strong>Generate the SDK</strong></h4>\n<p>With the model and a Rails service, it’s now time to generate the SDK. Smithy code generation and integration is only available in Java environments. Fortunately, for this demo, the High Score Service SDK has already been generated and committed to the smithy-ruby repo. Download it <a href=\"https://github.com/awslabs/smithy-ruby/tree/4cba34e43867a84272be12812d66cc032f92a966/codegen/projections/high_score_service\" target=\"_blank\">from here</a> if you are following along!</p>\n<p>If you’d like to generate it yourself, or generate your own Smithy model, you can follow the <a href=\"https://github.com/awslabs/smithy-ruby/blob/main/README.md#generating-an-sdk-for-a-rails-json-api\" target=\"_blank\">README instructions</a> that detail how to use smithy-ruby in your Gradle project.</p>\n<h4><a id=\"Use_the_SDK_249\"></a><strong>Use the SDK</strong></h4>\n<p>Now we have a Rails service and an SDK. Start up <code>irb</code> with <code>irb -I high_score_service/lib</code> and try it out!</p>\n<p>Ruby</p>\n<pre><code class=\"lang-\">require 'high_score_service'\n\n# Create an instance of HighScoreService's Client.\n# This is similar to the AWS SDK Clients.\n# Here we use the endpoint of the Rails service.\nclient = HighScoreService::Client.new(endpoint: 'http://127.0.0.1:3000')\n\n# List all high scores\nclient.list_high_scores\n# =&gt; #&lt;struct HighScoreService::Types::ListHighScoresOutput high_scores=[]&gt;\n\n# Try to create a high score\n# Should raise an UnprocessableEntityError, let's find out why\n begin\n client.create_high_score(high_score: { score: 9001, game: 'X' })\nrescue =&gt; e\n puts e.data\n # =&gt; #&lt;struct HighScoreService::Types::UnprocessableEntityError errors={&quot;game&quot;=&gt;[&quot;is too short (minimum is 2 characters)&quot;]}&gt;\nend\n\n# Actually create a high score\nclient.create_high_score(high_score: { score: 9001, game: 'Frogger' })\n# =&gt; #&lt;struct HighScoreService::Types::CreateHighScoreOutput\n\n# List high scores again\nresp = client.get_high_score(id: '1')\nresp.high_score\n# =&gt; #&lt;struct HighScoreService::Types::HighScoreAttributes id=1, game=&quot;Frogger&quot;, score=9001 ... &gt;\n</code></pre>\n<p>As an exercise, try out the <code>delete_high_score</code> and <code>update_high_score</code> operations.</p>\n<h3><a id=\"Future_Plans_287\"></a><strong>Future Plans</strong></h3>\n<p>Looking forward, smithy-ruby will be used to generate the new service client versions (gem version 2, core version 4) of AWS SDK For Ruby.</p>\n<p>We’d like to explore more Smithy Ruby and Rails API use cases. Perhaps a Smithy model can be parsed and translated into a set of <code>rails new</code> and <code>rails generate</code> commands; going further, perhaps a “server-side SDK” can be a pluggable Rails engine that handles building and parsing of concrete types and protocols.</p>\n<h3><a id=\"Feedback_292\"></a><strong>Feedback</strong></h3>\n<p>If you have any questions, comments, concerns, ideas, or other feedback, please create an issue or discussion in the <a href=\"https://github.com/awslabs/smithy-ruby\" target=\"_blank\">smithy-ruby repository</a>. We welcome any SDK design feedback and improvements, and we especially welcome any community contributions.</p>\n<p>Thanks for reading!</p>\n<p>-Matt</p>\n"}
目录
亚马逊云科技解决方案 基于行业客户应用场景及技术领域的解决方案
联系亚马逊云科技专家
亚马逊云科技解决方案
基于行业客户应用场景及技术领域的解决方案
联系专家
0
目录
关闭