<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Leverette on Medium]]></title>
        <description><![CDATA[Stories by Andrew Leverette on Medium]]></description>
        <link>https://medium.com/@andrewleverette?source=rss-f7bcd97839a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ebfes9cnsSK5RsVZR8Qc4g@2x.jpeg</url>
            <title>Stories by Andrew Leverette on Medium</title>
            <link>https://medium.com/@andrewleverette?source=rss-f7bcd97839a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:25:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewleverette/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to Apache Arrow with Rust]]></title>
            <link>https://levelup.gitconnected.com/introduction-to-apache-arrow-with-rust-394f391ea455?source=rss-f7bcd97839a------2</link>
            <guid isPermaLink="false">https://medium.com/p/394f391ea455</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[apache-arrow]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Leverette]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 00:37:12 GMT</pubDate>
            <atom:updated>2021-03-15T00:37:12.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kzNXhl3Nd1fLflT5BAfSQ.png" /></figure><p>For the past few months, I’ve been working on an application that is responsible for processing in-memory data. The project is exciting to me for two reasons. One is that the project is written entirely in Rust, and the other is the opportunity to learn about new topics and libraries. This article explores what I have learned while working with Apache Arrow.</p><p>When I first started working on the project, I was not aware of Apache Arrow. I just needed a way to aggregate data as efficiently as possible. I even built a proof-of-concept that provided most of the functionality that I needed, including joins. It was a rough draft, but I could already tell that there were some performance issues. One fundamental issue was the performance of aggregation functions on the data structure that represented a data set in a row-based format. This design meant that column-based operations like filtering and mathematical operations were costly. There were a few other concerns, so I decided to do some more research which finally led me to Apache Arrow.</p><h3>What is Apache Arrow</h3><p><a href="https://arrow.apache.org/">Apache Arrow</a> is a language-agnostic software development platform used to build applications that process and transport large data sets. Not only did this product provide a column-oriented data format, but it also provided a few other helpful libraries and a developer ecosystem maintained by the Apache Software Foundation.</p><h4>Memory Format</h4><p>The core feature of Apache Arrow is its in-memory columnar data format which is a specification for structuring tabular data sets in memory and provides a well-defined type system. This makes the format an ideal building block for projects like database systems or data frame libraries. One major benefit of this memory format is that it excels at processing large chunks of data and enables vectorization using SIMD operations.</p><h4>Libraries</h4><p>Other libraries are provided as companions to Apache Arrow. They provide common functionality that you wouldn’t want to implement yourself. Two Rust-specific libraries I found helpful were <a href="https://crates.io/crates/datafusion">DataFusion</a> and <a href="https://crates.io/crates/arrow-flight">Arrow Flight</a>. DataFusion is a query engine built on Apache Arrow that provides data frame and SQL query APIs. Arrow Flight is a serialization library that is used for transporting data across a network. I’ll go into more detail about these libraries in later articles.</p><h4>Developer Ecosystem</h4><p>One important factor in deciding on Apache Arrow was the developer ecosystem. Apache Arrow is maintained by the Apache Software Foundation which provides a governing body and decision-making process. The foundation also works to maintain a community of open-source developers that is open to everyone.</p><h3>Rust Arrow Implementation</h3><p>There are multiple implementations of Apache Arrow, but I will focus on the <a href="https://crates.io/crates/arrow">Rust version</a>. This section will be broken into four parts: low-level arrays, high-level constructs, data readers, and compute kernels. Not every aspect of the library will be covered but just enough to get a good idea of how it can be used.</p><h4>Low-Level Arrays</h4><p>The critical component of the Rust implementation is the Array trait. It represents a generic, fix-sized, immutable, thread-safe array of nullable elements. There are two ways to construct an Array: a converter method and a builder method.</p><p>The converter method is used to construct an Array instance from a vector of native Rust types. In my opinion, this method is the most common since iterating over a collection of data and collecting that data into a vector is very common. Using the converter method might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2Y-rZOwD0FW8gV4JBpF2Q.png" /><figcaption>A primitive array constructed with a converter</figcaption></figure><p>In this snippet, Int32Array is an Array that represents an array of optional 32-bit signed integers. The from method takes a vector of Option&lt;i32&gt;values to construct the array. There are several implementations of the Array trait, so be sure to check the documentation for the correct type of Array.</p><p>The builder method is a way to construct an array by appending values to it. This is useful for constructing arrays from values dynamically. Here is an example of using the builder method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxO1R0pLB85pmuh8QKywfA.png" /><figcaption>A primitive array constructed from a builder</figcaption></figure><p>In the above example, Int32Builder is used to initialize a builder instance that has a capacity of 100 elements. For the first 50 elements, the generated value is appended to the array if it is even, otherwise, a null is appended — this isn’t an actual null value. For the last 50 elements, the generated values are collected into a vector which is then appended to the array as a slice. The finish method converts the builder instance into an array instance.</p><h4>High-Level Constructs</h4><p>Arrays are an incredibly powerful abstraction for working with data. However, they do not provide an easy way to work with tabular data sets. That is where these high-level constructs come into the picture. Three data structures work together with low-level arrays to represent a data set:</p><ul><li>Field — Defines the metadata of a single column of data</li><li>Schema — Defines the metadata of a data set, contains a vector of Field</li><li>RecordBatch — Defines a two-dimensional data set that contains low-level arrays of the same length and a Schema that matches the array types</li></ul><p>The RecordBatch type offers a convenient interface for working with a data set and is the most common structure for tasks like computation and serialization. Below is an example of using these types to represent a data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCP07pGN7d4zrXnWX8Oy7Q.png" /><figcaption>A data set represented by RecordBatch, Schema, Field types</figcaption></figure><p>In the above example, the RecordBatch type becomes the top-level component that wraps the schema and the primitive arrays. One thing to note is that RecordBatch consists of atomically reference-counted pointers to the schema and individual primitive arrays. Using this type of reference is an important reason why Apache Arrow can provide zero-copy reads.</p><h4>Data Readers</h4><p>Having the ability to construct a data set from the core components of Apache Arrow has limited use cases. There is a definite need to read data into the Apache Arrow memory format without a tremendous amount of effort. In the Rust implementation of Apache Arrow, one of the data readers that are provided is a CSV reader.</p><p>The CSV reader reads the records from a CSV file then converts the columns into the appropriate primitive array type based on the schema. The CSV reader can either be used directly or generated from a builder object with custom settings. Using the CSV reader directly could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oG7_PF15Vk9dEk_0H5l9Hw.png" /><figcaption>Reading data with a CSV reader</figcaption></figure><p>In this example, a schema is defined that represents the data in the CSV file. The CSV reader is created using the opened file, a reference to the schema, and some configuration details like if the file has headers and the batch size. The batch size is an interesting parameter since that determines how many batches of records will be generated. For example, if you have a CSV file that contains 10,000 records, and the batch size is 1000 then the reader will eventually return a collection of 10 RecordBatch instances. Another interesting feature is that the CSV reader is an iterator. This means that the reader can be used in a for loop or any other iterative methods in Rust.</p><p>The CSV reader can also be generated from a builder object, which provides a bit more flexibility. Using the builder method could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yJ53PVPFUhlLKQGRnBGKg.png" /><figcaption>Constructing reader with a reader builder</figcaption></figure><p>This example demonstrates using ReaderBuilder to create a builder object that is configured to expect headers in the file and attempt to infer the schema from the first 100 records of the file. The build method will attempt to consume the builder and return a reader with a schema that matches what is in the file.</p><h4>Compute Kernels</h4><p>The compute kernels are the workhorses of Apache Arrow. Many kernel functions are provided, but this section will only cover the filter and sort functions in detail.</p><p>The filter function takes a reference to an array of data and an array of boolean values that indicate whether elements in that position should be filtered. To filter the arrays in a RecordBatch object, the filter function has to be applied to all the arrays using the same boolean array. For example, filtering the CSV data by the groupcolumn could look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roSTpTowSvBcDJhbEIexlw.png" /><figcaption>An example of using the filter method</figcaption></figure><p>In this example, a filter array is created by comparing each element of the groupcolumn to the value of the group parameter. Then the filter array is used to filter every column in the batch. A new RecordBatch instance is created and returned using the original schema and the filtered arrays.</p><p>Apache Arrow provides a few functions related to sorting. The relevant one to this example is the sort_to_indices function that takes a reference to an array of data and an optional SortOptions object and returns an array of unsigned integers that represent the new positions of the elements in the array. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nmep1AXt9E7l4Rq92IJxHQ.png" /><figcaption>An example using the sort method</figcaption></figure><p>This example builds an array of indices by calling the sort_to_indices function with a reference to the group column and no sort options. Then thetake function is mapped to all the columns to reorder the arrays based on the sorted indices. A new RecordBatch object is created and returned using the same schema and the sorted arrays.</p><p>The Apache Arrow library is focused on low-level operations. This means some common data aggregation operations aren’t part of the API. For example, there isn’t a group by function. However, group by functionality can be implemented with filters, sorts, and choice of aggregate functions. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fQ7ZNKk9GbppZKg6VqArw.png" /><figcaption>An example of implementing a group by</figcaption></figure><p>This example first finds the unique group column values by sorting the group column, collecting the values into a vector, and removing duplicate values. A vector of builder arrays is initialized to hold the average score for each score column. For each unique group, the filter_by_group function is used to find all the corresponding score values. The average is calculated for each column in that group and appended to the corresponding builder. The results of the builders are then collected, a new schema is created that represents the new structure, and a RecordBatch instance is returned.</p><h3>Final Thoughts</h3><p>There are many other topics to explore, but the main goal was to provide an overview of Apache Arrow and the Rust implementation. My experience with working with Apache Arrow was overwhelmingly positive. The library does not provide the high-level aggregation methods that you might need, but that is not the purpose of this library. It provides the building blocks, but you have to put them together.</p><h3>Thanks</h3><p>Thanks for reading! If you would like to connect or want to provide feedback, feel free to contact me on <a href="https://www.linkedin.com/in/andrewleverette/">LinkedIn</a>.</p><h3>Related Articles</h3><p><a href="https://levelup.gitconnected.com/working-with-csv-data-in-rust-7258163252f8">Working with CSV Data in Rust</a></p><h3>Resources</h3><ul><li><a href="https://mockaroo.com/42fd4a20">CSV file schema</a></li><li><a href="https://github.com/andrewleverette/data_wrangling_with_rust/tree/main/introduction_to_apache_arrow_with_rust">Code Examples</a></li><li><a href="https://arrow.apache.org/">Apache Arrow</a></li><li><a href="https://docs.rs/arrow/3.0.0/arrow/">Rust Arrow Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394f391ea455" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/introduction-to-apache-arrow-with-rust-394f391ea455">Introduction to Apache Arrow with Rust</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with GraphQL in Rust]]></title>
            <link>https://levelup.gitconnected.com/working-with-graphql-in-rust-dcbff7e768f1?source=rss-f7bcd97839a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcbff7e768f1</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Andrew Leverette]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-10-05T02:33:00.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjWm8Ddh48McbtTcJVZ08w.png" /></figure><p>GraphQL is a very popular framework for developing client-facing APIs. This article covers the basics of integrating GraphQL with Rust including designing a code-first schema, setting up a GraphQL server, and implementing custom resolvers and mutations.</p><h3>Why GraphQL and Rust</h3><p>The idea for this article spawned from what I’ve been doing at work recently. I normally spend my time writing Rust code, but I’ve recently been working with GraphQL in a TypeScript environment. The type system that GraphQL uses reminded me of structures in Rust which made me curious about using GraphQL and Rust together, so I decided to see what kind of support Rust had for working with GraphQL.</p><p>After a bit of research, I was able to find two libraries: <a href="https://crates.io/crates/async-graphql"><em>async-graphql</em></a> and <a href="https://crates.io/crates/juniper"><em>Juniper</em></a>. The <em>Juniper</em> library seems to be the go-to library according to <em>crates.io</em> statistics. It’s a fairly stable crate and supports a majority of GraphQL specifications. However, it doesn’t support <em>Subscriptions</em> or <em>async/await</em>, although both of these features are available in the master branch. The <em>async-graphql</em> library is newer and is increasing in popularity. It also supports GraphQL <em>Subscriptions</em> and <em>async/await</em> syntax. One drawback is <em>async-graphql</em> is going through rapid changes to its API, sometimes multiple releases within a day. Since this article isn’t about comparing these two crates, I decided to work with <em>Juniper</em> first since it is much more stable right now.</p><h3>What is GraphQL</h3><p>Just in case you aren’t familiar with GraphQL, I will give a brief overview before jumping into the rest of this tutorial. GraphQL is an API query language and a runtime for resolving those queries with the requested data. From a client perspective, GraphQL allows for a greater separation of concerns between the client and server-side resources. This means that a client doesn’t have to know the endpoint of any resource or even if two or more resources are related. The client can simply ask for the data that it needs it will get exactly that. On the server-side, a GraphQL API is implemented in terms of types and fields. The root type contains the name of the resources and what those resources return. Other types define data that can be returned from the resources in the root type. For a more in-depth look a GraphQL, I would recommend starting <a href="https://graphql.org/learn/">here</a>.</p><h3>Setup a Simple GraphQL Server</h3><p>Now that I’ve picked a GraphQL library, I also need a web framework to be able to handle the incoming GraphQL queries. Since <em>Juniper</em> doesn’t support <em>async/await</em> syntax, I decided to go with a web framework in a similar situation, <em>Rocket</em>. Like <em>Juniper</em>, <em>Rocket</em> does not support <em>async/await</em>, but that is due to change with its next release.</p><blockquote><em>Rocket requires the use of the nightly version of Rust. You can switch to the nightly version by running the command </em><em>rustup default nightly. If you want to switch back to stable, just run the command </em><em>rustup default stable.</em></blockquote><p>With the basics out of the way, I’ll start by setting up a new project using cargo new rust_graphql_example. Then in the <em>Cargo.toml</em> file, I&#39;ll add the following dependencies:</p><pre>juniper = &quot;0.14.2&quot; juniper_rocket = &quot;0.5.2&quot; rocket = &quot;0.4.5&quot;</pre><p>One thing to note is that <em>Juniper</em> provides some pre-built libraries for integrating with some web frameworks. For this example, I will use <a href="https://crates.io/crates/juniper_rocket"><em>juniper_rocket</em></a></p><blockquote><em>For a full list of supported integrations, take a look at the </em>Integrations<em> section in the </em><a href="https://docs.rs/juniper/0.14.2/juniper/index.html"><em>documentation</em></a><em>.</em></blockquote><h4>A Simple Schema</h4><p>The first thing to do is to define a simple GraphQL schema. So I created a new file called <em>schema.rs</em> in the <em>/src</em> directory and added the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*FQDpQYhaTSoyO00b.png" /></figure><p>There are three main pieces to a GraphQL schema: the query, the mutation, and the root node. The Query struct is used to define the resources that are available to GraphQL and defines how a query is resolved. The juniper::object procedural macro above the implementation block of Query is the primary way of defining GraphQL resolvers in <em>Juniper</em>. The Mutation type is just a placeholder for right now, but it will later define the resources that allow the client to mutate data. You&#39;ll notice that EmptyMutation is a generic struct. Later the unit type () will be replaced by the database context. Finally, the Schema basically merges the other two structures and becomes the root of the GraphQL schema.</p><h4>A Simple Webserver</h4><p>Now that a simple schema is defined, I need to set up the webserver. The <em>juniper_rocket</em> library makes that a little easier since it provides some pre-built integrations. In the <em>main.rs</em> file I added the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*_QAM1chiFkgBzmeG.png" /></figure><p>In this example, I’m setting up two endpoints: one for the GraphiQL interface, and the other for handling post requests from an actual client. The <em>juniper_rocket</em> integration is extremely helpful here since it provides simple request and response wrappers and an easy way to execute a GraphQL query. The juniper_rocket::graphiql_source function is nice as well since it allows you to easily set up the GraphiQL page in the application. The main function is just registering the Schema, mounting the routes, and then starting the webserver.</p><p>As a side note, one issue that I have with <em>Juniper</em> is that <em>EmptyMutation</em> is a generic structure. That means if I don’t provide an actual database context, like in this example, I have to set the template type as the unit type. In <em>Rocket</em> this means that I have to pass the unit type in Rocket::State and in the manage function. This seems unnecessary to me.</p><h4>Starting the Server</h4><p>Now I have a simple schema and a webserver to handle requests. To test it, simply run the command cargo run which will compile and start the server. Once the project finishes compiling, open a web browser and navigate to localhost:8000.</p><p>Welcome to GraphiQL! This tool supports writing and executing queries and schema introspection. The <em>Documentation Explorer</em> designated by the Docs button allows for schema introspection. This means I can drill down into the schema to see the resources, fields, and types available to GraphQL. This includes any parameters and documentation. The query window allows me to construct a query and execute it by pressing the play icon. For example, if I type the following query:</p><pre>{<br>  helloWorld<br>}</pre><p>The response from our GraphQL server is:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;helloWorld&quot;: &quot;Hello, world!&quot;<br>  }<br>}</pre><h3>Custom GraphQL Types</h3><p>Now I have a simple GraphQL schema and server set up. It also happens to be completely useless. For a more realistic example, I’m going to set up a GraphQL API that serves data about a list of clients of a consultant and their invoices. The data for this example is included in the repository in the /data directory. I have three data sources: <em>Clients.csv</em>, <em>Invoices.csv,</em> and <em>InvoiceItems.csv</em>. Invoices are related to a Client by the ClientId and InvoiceItems are related to Invoices by InvoiceId.</p><blockquote><em>All data is randomly generated using </em><a href="https://mockaroo.com/"><em>Mockaroo</em></a><em>.</em></blockquote><h4>Add Data Models</h4><p>The first thing I want to do is add three more dependencies to the project. Since I’m working with CSV data, I want to pull in the <em>csv</em> crate. Also, the Invoices.csv file contains dates, so I&#39;ll pull in the <em>chrono</em> crate. Lastly, I&#39;ll need to be able to deserialize the CSV data into a custom Rust type, so I want to pull in the <em>serde</em> crate. Add the following to the <em>Cargo.toml</em> file:</p><pre>chrono = { version = &quot;0.4.15&quot;, features=[&quot;serde&quot;] } csv = &quot;1.1&quot; serde = { version = &quot;1.0&quot;, features = [&quot;derive&quot;] }</pre><p>Then, I create a new file called <em>models.rs</em> and update <em>main.rs</em> with a module declaration:</p><pre>mod models;</pre><p>Then I update <em>models.rs</em> with the following structure definitions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/0*PpbR39rxxERRqunU.png" /></figure><h4>Add a DataContext</h4><p>The next task is to add logic to read the CSV data and make it accessible to the application. To do this, I create a file called <em>db.rs</em> and update <em>main.rs</em> with a module declaration:</p><pre>mod db;</pre><p>Then I update <em>db.rs</em> with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*WHUgjof1JyU7yyNM.png" /></figure><p>This provides a way to serve the data from the CSV files to the rest of the application, but GraphQL does not have any knowledge of this <em>DataContext</em> struct or any of the data models for that matter.</p><h4>Connect to Juniper</h4><p>The first thing to do here is to make <em>Juniper</em> aware that a structure is a GraphQL type. An easy way to do that is to use the provided macro juniper::GraphQLObject. Just for an example, I&#39;ll update the <em>Client</em> model to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*lh9hTmYwkjtvENUr.png" /></figure><p>Now <em>Juniper</em> is aware of the <em>Client</em> model, but it doesn’t know how to interface with the <em>DataContext</em> or query the client data. In order to do this I need to update <em>schema.rs</em> to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*advjY2ntfzCM0Gmh.png" /></figure><p>The above code does two things:</p><ul><li>make <em>Juniper</em> aware of <em>DataContext</em> by implementing juniper::Context</li><li>and create a GraphQL query called clients that uses a reference to <em>DataContext</em> to query client data</li></ul><p>I also need to make <em>Rocket</em> aware of <em>DataContext</em> by updating the context variables in the request handlers and add an instance of <em>DataContext</em> to be managed by <em>Rocket</em>. Update the <em>main.rs</em> with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*JGQrjDaEIHf0o7ed.png" /></figure><p>Now I should be able to compile and run this example. When I navigate to http://localhost:8000/, I can open the <em>Documentation Explorer</em> and click on <em>Query</em> and I&#39;ll see something like this:</p><pre>helloWorld: String! <br>Simple &quot;Hello, world!&quot; query </pre><pre>clients: [Client!]! <br>Client resource to query clients</pre><p>That means I can execute a query like this:</p><pre>{<br>  clients {<br>    clientId<br>    companyName<br>    contactName<br>    email<br>  }<br>}</pre><p>And get a response that looks something like this:</p><pre>{<br>&quot;data&quot;: {<br>  &quot;clients&quot;: [<br>    {<br>      &quot;clientId&quot;: &quot;07-3782546&quot;,<br>      &quot;companyName&quot;: &quot;Ward, McLaughlin and Hilpert&quot;,<br>      &quot;contactName&quot;: &quot;Helga Jarritt&quot;,<br>      &quot;email&quot;: &quot;hjarritt0@icio.us&quot;<br>    },<br>    {<br>      &quot;clientId&quot;: &quot;91-7491370&quot;,<br>      &quot;companyName&quot;: &quot;Hermiston, Kilback and Runolfsson&quot;,<br>      &quot;contactName&quot;: &quot;Leonie Willshear&quot;,<br>      &quot;email&quot;: &quot;lwillshear1@amazon.co.uk&quot;<br>    },<br>    {<br>      &quot;clientId&quot;: &quot;36-6951968&quot;,<br>      &quot;companyName&quot;: &quot;Feil-Lang&quot;,<br>      &quot;contactName&quot;: &quot;Franzen Zelake&quot;,<br>      &quot;email&quot;: &quot;fzelake2@go.com&quot;<br>    }<br>}</pre><p>This example allows me to query all the client data, but it doesn’t allow me to see any other data that is related to clients. What I need is a way to tell GraphQL that all my data models are related in some way.</p><h3>Custom GraphQL Resolvers</h3><p>This leads to the concept of GraphQL resolvers. Resolvers tell GraphQL how to retrieve data for a certain field of a GraphQL type. So for this example, I’m going to add the other two models — <em>Invoice</em> and <em>InvoiceItem</em> — to <em>Juniper</em> so that I can query all related data. To do this, I need a custom resolver for both the <em>Client</em> and <em>Invoice</em> models.</p><p>First, I need to update <em>models.rs</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*a56RC0K2IVnwliXL.png" /></figure><p>Basically, this just moves the macro juniper::GraphQLObject from the <em>Client</em> model to the <em>InvoiceItem</em> model.</p><p>Next, I update <em>schema.rs</em> with the custom resolvers for the <em>Client</em> and <em>Invoice</em> models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*sd44QJ62BBdO4LdJ.png" /></figure><p>The custom resolvers are defined by the impl blocks for <em>Client</em> and <em>Invoice</em>. They are nearly identical to the corresponding data models except for one field. <em>Client</em> has a function called invoices which returns any invoices associated with that client. <em>Invoice</em> has a function called invoice_items which returns any invoice items associated with that invoice.</p><p>Now, when I compile and run this example, I can look at the <em>Documentation Explorer</em> and see that <em>Client</em> is defined like:</p><pre>Information about a client </pre><pre>clientId: String! <br>companyName: String! <br>contactName: String! <br>contactTitle: String! <br>phone: String! <br>email: String! <br>invoices: [Invoice!]!</pre><p>And <em>Invoice</em> is defined as:</p><pre>Information about an invoice for a specific client </pre><pre>invoiceId: Int! <br>invoiceNumber: String! <br>clientId: String! <br>invoiceDate: NaiveDate! <br>dueDate: NaiveDate! <br>invoiceItems: [InvoiceItems!]!</pre><p>This means that I can execute a query like this:</p><pre>{ <br>  clients { <br>    clientId <br>    companyName <br>    contactName<br>    email <br>    invoices { <br>      invoiceNumber <br>      invoiceDate <br>      dueDate <br>      invoiceItems { <br>        productId <br>        description <br>        price <br>      } <br>    } <br>  } <br>}</pre><p>And get a result that looks like the following:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;clients&quot;: [<br>      {<br>        &quot;clientId&quot;: &quot;07-3782546&quot;,<br>        &quot;companyName&quot;: &quot;Ward, McLaughlin and Hilpert&quot;,<br>        &quot;contactName&quot;: &quot;Helga Jarritt&quot;,<br>        &quot;email&quot;: &quot;hjarritt0@icio.us&quot;,<br>        &quot;invoices&quot;: [<br>          {<br>            &quot;invoiceNumber&quot;: &quot;INV100001&quot;,<br>            &quot;invoiceDate&quot;: &quot;2020-01-31&quot;,<br>            &quot;dueDate&quot;: &quot;2020-02-29&quot;,<br>            &quot;invoiceItems&quot;: [<br>              {<br>                &quot;productId&quot;: 7929,<br>                &quot;description&quot;: &quot;leverage back-end e-business&quot;,<br>                &quot;price&quot;: 3315.33<br>              }<br>            ]<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><h3>Efficient GraphQL Queries</h3><p>There is one big problem with this design, however. Assuming that invoice data is likely going to be requested, the design is very inefficient. For every client record, a query is made to get all that client’s invoices. For every invoice record, a query is made to get the invoice detail for that invoice. This is known is the N + 1 query problem and leads to looking for efficient ways of performing queries.</p><p>One way to solve this issue is to decouple the data models from the GraphQL types. There are a couple of libraries that are available that can help with this issue for example:</p><ul><li><a href="https://crates.io/crates/dataloader">dataloader</a></li><li><a href="https://crates.io/crates/juniper-eager-loading">juniper-eager-loading</a></li></ul><p>However, I wanted to focus on just <em>Juniper</em> integration so I decided to implement a simple solution for this example.</p><p>There two things I need to do to make this work. The first task is to define GraphQL types in are separate from the data models but allow for relational data. The second task is to update the clients query to pull all the data and correctly map the data based on the relational ids from the data models. I update <em>schema.rs</em> to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/0*b3sZQ_E1dafRK8MO.png" /></figure><p>The GraphQL types are pretty straight forward, but I wanted to walk through the clients query. The goal is to get all the data upfront so that subsequent queries are not necessary. The way that I have done that is to use two hash maps - one for clients and one for invoices. I create the client hash map first and initialize the invoices field to an empty vector. Then I create the invoice map, I only add the invoices that have a client_id in the client map and set the invoice_items field to an empty vector. Then I can map the invoice items data to the appropriate invoice in the invoice map and the invoices to the appropriate client. After all the data is queried and mapped properly, I return the list of clients.</p><h4>Adding Query Parameters</h4><p>The example above returns a list of all client data. Depending on the amount of data, this may be a very bad idea. GraphQL provides the ability to pass in arguments to the queries. For example, I could use arguments to implement pagination or add another query to look up a client by id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/0*_aSGVcY9wN2OKlnN.png" /></figure><p>This example adds simple pagination logic to the clients query by adding first and offset as parameters. Those parameters are then used in the skip and take functions. GraphQL provides a more in-depth pagination guide <a href="https://graphql.org/learn/pagination/">here</a>.</p><p>The get_client query is added and has similar logic to clients except that it will only ever return at most a single client. Also, the return type of get_client is an Option. This means that if the id parameter does not match an existing client, the response will look like this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;getClient&quot;: null<br>  }<br>}</pre><h3>GraphQL Mutations</h3><p>Now I can perform two separate queries on the data set. However, I don’t have a way to change the state of the data. GraphQL provides a method to modify server-side data using <a href="https://graphql.org/learn/queries/#mutations">Mutations</a>.</p><h4>Adding Mutations in Juniper</h4><p>In the context of <em>Juniper</em>, the implementation of a mutation is similar to the implementation of a query. To add the implementation of Mutation I replace this line:</p><pre>pub type Mutation = EmptyMutation&lt;DataContext&gt;;</pre><p>with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*id-3EP1GWDdD0RjZ.png" /></figure><p>This example defines an empty structure called Mutation and adds an implementation block with the juniper::object attribute. It also declares to GraphQL Input types called NewClient and NewInvoiceItem. In the implementation block there are three functions that are stubbed out currently but will be implemented later.</p><p>Since Mutation is being change from a type to a structure, two small changes need to be made. First, I need to update the Schema type:</p><p>I also need to update how Schema is being instantiated in the main function like so:</p><pre>fn main() {<br>  rocket::ignite()<br>    .manage(DataContext::init().unwrap())<br>    .manage(Schema::new(Query, Mutation))<br>    .mount(<br>      &quot;/&quot;,<br>      rocket::routes![graphiql, get_graphql_handler, post_graphql_handler],<br>    )<br>    .launch();<br>}</pre><p>Now the new Mutation will be registered with <em>Juniper</em>, but it doesn&#39;t do anything yet. However, before I can implement the functions within Mutation I have to make some changes to allow DataContext to be mutable within the function call.</p><h4>Mutable Context</h4><p>The Context object that I instantiate within the juniper::object macro is immutable. This is a problem since that means the data inside the context object is also immutable. What I really want to do is change the state of the interior data which means I need interior mutability that is also thread-safe.</p><p>In order for the context object to support interior mutability, I need to wrap the properties of DataContext in an Arc and Mutex. In <em>db.rs</em>, I update DataContext to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*BJJub9_azf5e-V7Q.png" /></figure><p>By adding that Arc and Mutex wrappers, I can safely mutate data within DataContext. However, that does break every function within Query. To fix this, I need to update the clients and get_client queries to use the new version of the context object.</p><p>I updated clients to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*7NJo9ptB-Np9VIwN.png" /></figure><p>And get_clients to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/0*UEqH7LCE07q6fuZY.png" /></figure><p>This will fix the issues caused by changing the DataContext implementation.</p><h4>Add Mutation Function Definition</h4><p>Now I can implement the functions in the Mutation. This is a bit of a contrived example so I&#39;m not going to write the updates back to the file, but any changes will live as long as the server is active. Also, each mutation will just return the instance of the object if it was added successfully.</p><p>For add_client, I add the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*7c-qJhEAk56UHxwJ.png" /></figure><p>There’s nothing special about this one. It creates an instance of the GraphQL Client type to return to the caller. It also creates and adds an instance of ClientModel to the clients property of DataContext.</p><p>For add_invoice, there&#39;s a bit more going on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/0*25qKUQAKGTOhoUK9.png" /></figure><p>This one finds the invoice with the maximum invoice id and increments it by one to generate a new invoice id and invoice number. Then it uses chrono::Local::today to get the current month and year to calculate the invoice date (last day of the current month) and the due date (last day of the following month). From there, it&#39;s similar to add_client. An instance of the GraphQL Invoice is created and an instance of InvoiceModel is added to the invoices property of DataContext.</p><p>Finally, add_invoice_item:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*drhu68I0EqCepXd7.png" /></figure><p>Like add_invoice, add_invoice_item finds the maximum item id and increments it to get a new item id. Then creates an instance of the GraphQL type InvoiceItem and adds an instance of InvoiceItemModel is added to the invoice_items property of DataContext.</p><h4>Running the Mutations</h4><p>With all the mutation methods defined, I can test them out now. First start the server by running the command cargo run. Then, if I want to add a new client, the mutation that I would execute could look something like this:</p><pre>mutation {<br>  addClient(<br>    newClient: {<br>      clientId: &quot;99-5344573&quot;<br>      companyName: &quot;Herman-Treutel&quot;<br>      contactName: &quot;Ario Drayson&quot;<br>      contactTitle: &quot;Business Systems Development Analyst&quot;<br>      phone: &quot;499-304-2835&quot;<br>     email: &quot;wclaricoats0@ftc.gov&quot;<br> }) {<br>    clientId<br>    companyName<br>    contactName<br>    contactTitle<br>    phone<br>    email<br>  }<br>}</pre><p>And I would get a response that looks like this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;addClient&quot;: {<br>      &quot;clientId&quot;: &quot;99-5344573&quot;,<br>      &quot;companyName&quot;: &quot;Herman-Treutel&quot;,<br>      &quot;contactName&quot;: &quot;Ario Drayson&quot;,<br>      &quot;contactTitle&quot;: &quot;Business Systems Development Analyst&quot;,<br>      &quot;phone&quot;: &quot;499-304-2835&quot;,<br>      &quot;email&quot;: &quot;wclaricoats0@ftc.gov&quot;<br>    }<br>  }<br>}</pre><p>I could then add an invoice to the new client by executing this mutation:</p><pre>mutation {<br>  addInvoice(clientId: &quot;99-5344573&quot;) {<br>    invoiceId<br>    invoiceNumber<br>    invoiceDate<br>    dueDate<br>  }<br>}</pre><p>Which would return the following:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;addInvoice&quot;: {<br>      &quot;invoiceId&quot;: 101001,<br>      &quot;invoiceNumber&quot;: &quot;INV101001&quot;,<br>      &quot;invoiceDate&quot;: &quot;2020-09-30&quot;,<br>      &quot;dueDate&quot;: &quot;2020-10-31&quot;<br>    }<br>  }<br>}</pre><p>Then to add an invoice item, I can run the add_invoice_item mutation:</p><pre>mutation {<br>  addInvoiceItem(<br>    invoiceId: 101001<br>    newInvoiceItem: {<br>      productId: 2899<br>      description: &quot;exploit e-business supply-chains&quot;<br>      price: 4969.04<br>    }<br>  ) {<br>    itemId<br>    invoiceId<br>    productId<br>    description<br>    price<br>  }<br>}</pre><p>And the response would be:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;addInvoiceItem&quot;: {<br>      &quot;itemId&quot;: 6001,<br>      &quot;invoiceId&quot;: 101001,<br>      &quot;productId&quot;: 2899,<br>      &quot;description&quot;: &quot;exploit e-business supply-chains&quot;,<br>      &quot;price&quot;: 4969.04<br>    }<br>  }<br>}</pre><h3>Review</h3><p>Overall, <em>Juniper</em> is a well-designed library to provide GraphQL support in Rust and I enjoyed working with it. The integrations are extremely beneficial and most of the types are well structured. My two favorite features are the juniper::object attribute and the GraphQL type macros.</p><p>There is one thing that I would love to see with this library — a new release. There hasn’t been a version release since December of 2019. There have been changes to the repo since then like support for async/await syntax and GraphQL Subscriptions. Hopefully, a new release will be out soon.</p><p>All code is available <a href="https://github.com/andrewleverette/rust_graphql_example">here</a>.</p><h3>Thanks</h3><p>Thanks for reading! If you would like to connect or want to provide feedback, feel free to contact me on <a href="https://www.linkedin.com/in/andrewleverette/">LinkedIn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*3N6R_9KQPVOHCiYG66Iytg.png" /></figure><p><em>Originally published at </em><a href="https://andrewleverette.github.io/graphql-and-rust/"><em>https://andrewleverette.github.io</em></a><em> on October 1, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcbff7e768f1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/working-with-graphql-in-rust-dcbff7e768f1">Working with GraphQL in Rust</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with CSV Data in Rust]]></title>
            <link>https://levelup.gitconnected.com/working-with-csv-data-in-rust-7258163252f8?source=rss-f7bcd97839a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7258163252f8</guid>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[aggregation]]></category>
            <dc:creator><![CDATA[Andrew Leverette]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-07-03T13:47:13.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wB9URXuyb-XnU_728RUujg.png" /></figure><p>The CSV file format is a very common method for storing tabular data. This article covers the basics of reading and writing CSV files, (de)serializing CSV data using the Serde library, and wraps up with a sample data aggregation example.</p><h3>Introduction</h3><p>The idea for this article came about because I needed a fast and convenient way to work with CSV formatted data. One option was to write my own library, but I didn’t feel like that was a convenient solution. So, after a bit of research, I decided to use the <a href="https://crates.io/crates/csv">csv</a> crate authored by <a href="https://github.com/BurntSushi">Andrew Gallant</a>. I chose this crate because the API is fairly straight forward and, most importantly to me, the documentation is very thorough.</p><h3>Setup</h3><p>To use this crate, simply create a new Rust project using cargo new and add this under [dependencies] in the Cargo.toml file:</p><pre>csv = &quot;1.1&quot;</pre><p>Also, part of this article will utilize Serde’s custom derive functionality, so go ahead and add this as well:</p><pre>serde = { version = &quot;1&quot;, features = [&quot;derive&quot;] }</pre><h3>Data Sources</h3><p>All data in this article is generated from <a href="https://mockaroo.com/">Mockaroo</a>, which is a free mock data service that is very flexible and easy to use and share. The schemas I will be using can be found at the following links:</p><blockquote><em>One quick note about the </em><em>Order schema. It has a foreign key relationship to the </em><em>Customer schema. To set that up on the Mockaroo site, create the </em><em>Customer schema first, download it as a csv file, upload the csv file as a data set, then you can create the </em><em>Order schema.</em></blockquote><h3>Reading CSV Data</h3><p>The csv crate provides a Reader structure that is used to transform raw CSV data into standard Rust types. The Reader has the functionality to read from an input stream or a file and deserialize data into a custom structure using Serde.</p><h4>Reading from stdin</h4><p>Reading from stdin may not be a common use case unless you are passing CSV data into a command line application. To read from stdin, the crate provides a function called from_reader. This method works for any type that implements the trait which means you could read from an array of bytes into a Reader. The following example shows how to read CSV data from stdin:</p><p><a href="https://github.com/andrewleverette/rust_csv_examples/blob/master/src/bin/csv_read_stdin.rs"><em>/src/bin/csv_read_stdin.rs</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*x5U_T5RjSKlE5n0z.png" /></figure><p>Once this code has been compiled, it can be called by passing it the downloaded CSV file. For example, I compiled the above using cargo build --release and was able to run it by type this into the terminal:</p><pre>./target/release/read_csv_stdin &lt; data/Customers.csv</pre><p>The output will look something like this:</p><pre>StringRecord([&quot;26fa5a49-5194-40eb-8faf-219c9fff831e&quot;, &quot;Arline&quot;, &quot;Jardine&quot;, &quot;ajardine0@vimeo.com&quot;, &quot;61635 Dawn Hill&quot;]) StringRecord([&quot;708fcc04-e387-47e3-b85d-99ccd4e18320&quot;, &quot;Baillie&quot;, &quot;Pierri&quot;, &quot;bpierri1@people.com.cn&quot;, &quot;70540 Gerald Way&quot;]) StringRecord([&quot;9a8ffa76-0280-4754-b75c-4de7508cdd67&quot;, &quot;Jenda&quot;, &quot;Print&quot;, &quot;jprint2@umn.edu&quot;, &quot;928 Bluestem Parkway&quot;]) StringRecord([&quot;c5b4b822-2b59-435f-a697-6f1d4bbb0684&quot;, &quot;Lucia&quot;, &quot;Rhucroft&quot;, &quot;lrhucroft3@techcrunch.com&quot;, &quot;212 Schiller Pass&quot;]) StringRecord([&quot;f266b61e-534f-483b-9f70-0029b7424aa8&quot;, &quot;Sybila&quot;, &quot;Valdes&quot;, &quot;svaldes4@google.com.au&quot;, &quot;2 Gateway Avenue&quot;])</pre><p>One thing you may have noticed is that .records() does not include the header row. That method skips the first row because it is interpreted as the header record by default. The Reader structure has a separate method called .headers() to retrieve the header record.</p><h4>Reading from File</h4><p>Reading from a file is probably the most common use case for the Reader structure. The crate provides a method called from_path which creates a Reader from the CSV data file path. The code to read from a file looks very similar to the code to read from stdin. The following example shows how to read CSV from a file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*OjMoSodAjqHmAnV_.png" /></figure><h4>Reading with Serde</h4><p>A convenient feature for this crate is the support for Serde which provides functionality to read CSV data and deserialize it into custom Rust data types. For example, the raw Customer data which looks like this -</p><pre>customer_guid,first_name,last_name,email,address 26fa5a49-5194-40eb-8faf-219c9fff831e,Arline,Jardine,ajardine0@vimeo.com,61635 Dawn Hill</pre><p>- can be deserialized into a Rust structure that looks like this:</p><pre>struct Customer {<br>    customer_guid: String,<br>    first_name: String,<br>    last_name: String,<br>    email: String,<br>    address: String<br>}</pre><p>Instead of using the .records method, like in the previous example. The Reader structure provides another method called .deserialize to create an iterator over each deserialized record. The following example shows how to read CSV data and deserialize it into a Rust type:</p><p><a href="https://github.com/andrewleverette/rust_csv_examples/blob/master/src/bin/csv_read_serde.rs"><em>/src/bin/csv_read_serde.rs</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*u4k5QUadP6Cyst8Q.png" /></figure><p>One important thing to note is that deserializing data comes with some inherent overhead. If you compare the first two examples to this one, you’ll find that deserializing data will be slower.</p><h4>Handling Invalid Data with Serde</h4><p>The previous examples have all been assuming fairly clean data. However, the CSV file format enforces no such assumptions. So if we try to deserialize data that can’t be converted into the declared type then there will be an error.</p><p>For example, for the Orders schema, the Rust structure could look something like this:</p><p>Then let’s assume that there is a record that looks like this:</p><pre>order_guid,customer_guid,order_date,total 02a771c1-9885-40d6-9acc-75cd108e9218,022d6000-b4da-412b-ba7c-cd0dbf868af9,4/16/2020,Null</pre><p>When Serde tries to deserialize the Null value, an error will occur that looks like this:</p><pre>CSV deserialize error: record 1 (line: 2, byte: 42): field 3: invalid float literal</pre><p>To fix this issue, the crate provides a helper function that can be applied to Option fields that tells Serde to convert the value to None if an error occurs. Adding that functionality looks like this:</p><pre>#[derive(Debug, Deserialize)]<br>struct Order {<br>    order_guid: String,<br>    customer_guid: String,<br>    order_date: String,<br><br>    #[serde(deserialize_with = &quot;csv::invalid_option&quot;)]<br>    total: Option&lt;f64&gt;<br>}</pre><p>Other than the invalid_option helper method, the rest of the code is exactly the same as the previous example.</p><h3>Writing CSV Data</h3><p>Writing CSV data is a bit more straight-forward than reading it since you have more control over the output. The crate provides a Writer structure which has a very similar interface to the Reader structure. The Writer structure provides functionality to write to stdout, write to a file, and serialize Rust types into CSV data.</p><h4>Writing to stdout</h4><p>A simple use case might be to write CSV data to stdout so that it can be piped into another application. To write to stdout, the crate provides the from_writer method to create a Writer structure configured to write to stdout. Once the Writer structure is created, records are added by calling the write_record method on the Writer instance. The following shows how to write CSV data to stdout:</p><p><a href="https://github.com/andrewleverette/rust_csv_examples/blob/master/src/bin/csv_write_stdout.rs"><em>/src/bin/csv_write_stdout.rs</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kCfOy-7yV5YDf1aL.png" /></figure><p>Since this just writes to stdout, the program can be called like this:</p><pre>./target/release/csv_write_stdout</pre><p>Or you could pipe into a file like this:</p><pre>/target/release/csv_write_stdout &gt; test.csv</pre><h4>Writing to File</h4><p>Another use case for writing CSV data is writing to a file. The csv crate provides the from_path method to create a Writer structure to write to the given file. Other than the from_path method, this example is the same as writing to stdout.</p><p><a href="https://github.com/andrewleverette/rust_csv_examples/blob/master/src/bin/csv_write_file.rs"><em>/src/bin/csv_write_file.rs</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f3wI-EABg2euvmoX.png" /></figure><h4>Writing with Serde</h4><p>Similarly to the Reader structure, the Writer structures supports serializing data from Rust types into CSV records using Serde. This example reuses the Customer schema from before, and converts instances of Customer into CSV data.</p><p><a href="https://github.com/andrewleverette/rust_csv_examples/blob/master/src/bin/csv_write_serde.rs"><em>/src/bin/csv_write_serde.rs</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*WhoCDVwin_t5rtKb.png" /></figure><p>The key difference in this example compared to the other write examples is the use of the serialize method instead of the write_record method to write data.</p><h3>CSV Aggregation</h3><p>When working with CSV data, a common use case is to read a CSV file, process the data, and then write the results back to a file. This example reads two CSV files, performs an inner join, and then writes the result to a file. Since this example is longer than the others, I just want to highlight a couple of sections, but the source code can be found <a href="https://github.com/andrewleverette/rust_csv_examples/blob/master/src/bin/csv_aggregation.rs">here</a>.</p><p>The first thing I decided to do was to define a structure to hold the headers and records to make performing the aggregation a little easier. That structure looks like this:</p><pre>#[derive(Debug)]<br>struct DataSet {<br>    /// Header row of CSV file<br>    headers: StringRecord,<br><br>    /// Records from CSV file<br>    records: Vec&lt;StringRecord&gt;,<br>}</pre><p>The StringRecord type, is the structure from the csv crate that defines a record. Using this type in DataSet allows for easy integration with the Reader and Writer internals when reading and writing CSV data.</p><p>To join these two data sets, I’m going to use a sort-merge join algorithm. Basically it sorts both data sets on a given column, and then scans both data sets looking for matches. When a match is found, it merges the records from both data sets into a single record and adds it to a new data set.</p><p>Since I have a custom structure that holds the records, I can add an impl block with a function to sort the records in a data set.</p><pre>/// Sort data records by the given index.<br>///<br>/// # Errors<br>///<br>/// An error occurs if the index is out of bounds<br>fn sort_by_index(&amp;mut self, index: usize) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    if index &gt;= self.headers.len() {<br>        Err(Box::new(IndexError(format!(<br>            &quot;Index &#39;{}&#39; out of bounds&quot;,<br>            index<br>        ))))<br>    } else {<br>        self.records.sort_by(|a, b| a[index].cmp(&amp;b[index]));<br>        Ok(())<br>    }<br>}</pre><p>Once both data sets have been sorted, I can join the data sets together. The core logic of the inner join method looks like this:</p><pre>let mut left_cursor = 0;<br>let mut right_cursor = 0;<br><br>while left_cursor &lt; self.records.len() &amp;&amp; right_cursor &lt; right.records.len() {<br>    // If two fields match, merge fields into a single record<br>    // and add to records vector<br>    // If they don&#39;t match and the left value is less then right value advance the left cursor<br>    // else advance the right cursor<br>    if self.records[left_cursor][left_index] == right.records[right_cursor][right_index] {<br>        let record = StringRecord::from(<br>            self.records[left_cursor]<br>                .iter()<br>                .chain(right.records[right_cursor].iter())<br>                .collect::&lt;Vec&lt;&amp;str&gt;&gt;(),<br>        );<br><br>        records.push(record);<br><br>        // Since data sets are sorted<br>        // Advance cursor through right data set to<br>        // see if there are matches<br>        let mut k = right_cursor + 1;<br>        while k &lt; right.records.len()<br>            &amp;&amp; self.records[left_cursor][left_index] == right.records[k][right_index]<br>        {<br>            let record = StringRecord::from(<br>                self.records[left_cursor]<br>                    .iter()<br>                    .chain(right.records[k].iter())<br>                    .collect::&lt;Vec&lt;&amp;str&gt;&gt;(),<br>            );<br><br>            records.push(record);<br><br>            k += 1;<br>        }<br><br>        left_cursor += 1;<br>    } else if self.records[left_cursor][left_index]<br>        &lt; right.records[right_cursor][right_index]<br>    {<br>        left_cursor += 1;<br>    } else {<br>        right_cursor += 1;<br>    }<br>}</pre><p>The sort-merge algorithm is one of many for efficiently joining data sets. If you want to read more on these types of algorithms, I found that <a href="http://blog.felipe.rs/2019/01/29/demystifying-join-algorithms/">this</a> article was a good starting point.</p><h3>Review</h3><p>Overall, I think the csv crate is very easy to work with and it is my first choice when I want a fast CSV parsing library. The crate benefits from well documented source code and a thorough tutorial document that goes into more detail. The Rust community seems to feel the same way since this crate has been downloaded over 3 million times.</p><h3>Thanks</h3><p>Thanks for reading! If you would like to connect or want to provide feedback, feel free to contact me on <a href="https://www.linkedin.com/in/andrewleverette/">LinkedIn</a>.</p><p><em>Originally published at </em><a href="https://andrewleverette.github.io/working-with-csv-data/"><em>https://andrewleverette.github.io</em></a><em> on June 30, 2020.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*3N6R_9KQPVOHCiYG66Iytg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7258163252f8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/working-with-csv-data-in-rust-7258163252f8">Working with CSV Data in Rust</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an API using Toki and Warp]]></title>
            <link>https://levelup.gitconnected.com/building-an-api-using-warp-and-tokio-26a52173860a?source=rss-f7bcd97839a------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a52173860a</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Andrew Leverette]]></dc:creator>
            <pubDate>Thu, 21 May 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-07-03T13:45:10.737Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an API with Rust using Tokio and Warp</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWv4hVJ33aA-nfPXtHpcfQ.png" /></figure><p>A sample project that uses Warp and Tokio to build a simple asynchronous API.</p><p>This tutorial introduces the Warp framework by building an asynchronous CRUD API. I wrote this with the following goals in mind:</p><ol><li>Become familiar with the Warp framework.</li><li>Become more familiar with using async/await in Rust</li><li>Get a better understanding of API design in Rust</li></ol><h3>Design</h3><p>Before getting into any coding, I’ll sketch out the design of the API. This will help with determining the necessary endpoints, handler functions, and how to store data.</p><h4>Routes</h4><p>For this API, I only need two routes.</p><pre>/customers <br>    - GET -&gt; list all customers in data store - POST -&gt; create new customer and insert into data store <br>/customers/{guid} <br>    - GET -&gt; list info for a customer <br>    - POST -&gt; update information for a customer <br>    - DELETE -&gt; remove customer from data store</pre><h4>Handlers</h4><p>Based on the defined routes, I will need the following handlers:</p><pre>list_customers -&gt; return a list all customers in database create_customer -&gt; create a new customer and add it to the database get_customer -&gt; return the details of a single customer update_customer -&gt; update the details of a single customer delete_customer -&gt; delete a customer from the database</pre><h4>Database</h4><p>For right now, I’ll just use an in-memory data store to share across the route handlers.</p><p>I used <a href="https://www.mockaroo.com/">Mockaroo</a> to generate a JSON data set of customer data. The data is a JSON array where each object has the following structure:</p><pre>{<br>    &quot;guid&quot;: &quot;String&quot;,<br>    &quot;first_name&quot;: &quot;String&quot;,<br>    &quot;last_name&quot;: &quot;String&quot;,<br>    &quot;email&quot;: &quot;String&quot;,<br>    &quot;address&quot;: &quot;String&quot;<br>}</pre><p>Also, the database module will need to have the ability to initialize the data store once the server starts.</p><h3>Dependencies</h3><p>As of right now, I know that I will need the following dependencies:</p><ul><li><a href="https://crates.io/crates/warp">Warp</a> — A web server framework for Rust</li><li><a href="https://crates.io/crates/tokio">Tokio</a> — An asynchronous run-time for Rust</li><li><a href="https://crates.io/crates/serde">Serde</a> — A de/serialization library for converting JSON to typed data and vice versa.</li></ul><h3>Implementation</h3><h4>Models</h4><p>The first thing I want to do is define my customer model and also start adding some structure to the code.</p><p>In main.rs, define a new module called models like this:</p><pre>mod models;<br><br>fn main() {<br>    // ...<br>}</pre><p>Then create a new file called models.rs and add the following:</p><pre>pub struct Customer {<br>    pub guid: String,<br>    pub first_name: String,<br>    pub last_name: String,<br>    pub email: String,<br>    pub address: String,<br>}</pre><p>Since I’m designing an API, this data structure needs be able to covert to and from JSON. I also want to be able to copy the structure into and out of the data store without having to worry about the borrow checker.</p><p>To accomplish this, I’ll add a derive statement to use a couple of the macros from the Serde library and a couple from Rust. Now models.rs looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*sue-KWrU-R1S1vwg.png" /></figure><h4>Database</h4><p>The database for this example API will be an in-memory database that is a vector of the Customer model. However, the data store will need to be shared across multiple routes, so we can use one of Rust&#39;s smart pointer along with a Mutex to allow for thread safety.</p><p>First, update main.rs with a new module called db:</p><pre>mod db;<br>mod models;<br><br>fn main() {<br>    // ...<br>}</pre><p>Then create a new file called db.rs.</p><p>There are a few things to do in this file, but the first thing to do is to define what the data store will look like.</p><p>A simple data store is just a vector of Customer structs, but it needs to be wrapped in a thread safe reference to be able to use multiple references of the data store in multiple asynchronous handlers.</p><p>Add the following to db.rs:</p><pre>use std::sync::Arc;<br>use tokio::sync::Mutex;<br><br>use crate::models::Customer;<br><br>pub type Db = Arc&lt;Mutex&lt;Vec&lt;Customer&gt;&gt;&gt;;</pre><p>Now that we have defined the structure of the data store, we need a way to initialize the data store. Initializing the data store has two outcomes, either an empty data store or a data store loaded with data from a data file.</p><p>An empty store is rather straight forward.</p><pre>pub fn init_db() -&gt; Db {<br>    Arc::new(Mutex::new(Vec::new()))<br>}</pre><p>But in order to load data from a file, we need to add another dependency:</p><ul><li><a href="https://crates.io/crates/serde_json">serde_json</a> — For reading raw JSON</li></ul><p>Add the following to the Cargo.toml file:</p><pre>serde_json = &quot;1.0&quot;</pre><p>Now we can update db.rs with the following:</p><pre>use std::fs::File;<br>use serde_json::from_reader;<br><br>pub fn init_db() -&gt; Db {<br>    let file = File::open(&quot;./data/customers.json&quot;);<br>    match file =&gt; {<br>        Ok(json) =&gt; {<br>            let customers = from_reader(json).unwrap();<br>            Arc::new(Mutex::new(customers))<br>        },<br>        Err(_) =&gt; {<br>            Arc::new(Mutex::new(Vec::new()))<br>        }<br>    }<br>}</pre><p>This function attempts to read from the file at ./data/customers.json. If it is successful, the function returns a data store loaded with the customer data, else it returns an empty vector.</p><p>The db.rs should look like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*VkFMRfyUv7oWLHhL.png" /></figure><h4>Handlers</h4><p>At this point we have the models and the database setup. Now we need a way to tie them together. That’s where the handlers come in.</p><p>First let’s define a new module in main.rs and create a new file called handlers.rs.</p><pre>mod handlers;</pre><p>We also need to add a couple of imports. In the handlers.rs file add the following:</p><pre>use std::convert::Infallible;<br>use warp;<br><br>use crate::models::Customer;<br>use crate::db::Db;</pre><p>This snippet makes the Customer model and Db type we have defined in the other modules available in the handlers module. It also imports the root warp module and the <a href="https://doc.rust-lang.org/std/convert/enum.Infallible.html">Infallible</a> enum, which is the error type for errors that can never happen.</p><p>Now as a reminder, here are the handlers we want to implement:</p><ul><li>list_customers -&gt; return a list all customers in database</li><li>create_customer -&gt; create a new customer and add it to the — database</li><li>get_customer -&gt; return the details of a single customer</li><li>update_customer -&gt; update the details of a single customer</li><li>delete_customer -&gt; delete a customer from the database</li></ul><h4>List Customers</h4><p>The list_customers handler will take a reference to the data store as an argument and return a Result type that wraps a JSON response.</p><p>The function definition will look like this:</p><pre>pub async fn list_customers(db: Db) -&gt; Result&lt;impl warp::Reply, Infallible&gt; {<br>   // ... <br>}</pre><p>For the function body, we need to get the customer list out of the data store and return it as a JSON object. For convenience, warp provides a reply method that will convert a vector to a json object.</p><p>Update the function with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*uuRtqjJYa_2q87XG.png" /></figure><p>The line let customers = db.lock().await; causes the current task to yield until a lock can be acquired and the data store can be referenced safely.</p><p>The line let customers: Vec&lt;Customer&gt; = customers.clone() takes the inner vector out of the MutexGuard.</p><p>The last line Ok(warp::reply::json(&amp;customers)) wraps a JSON reply in an Ok variant of the Result type.</p><h4>Create Customer</h4><p>The create_customer handler will take a Customer object and a reference to the data store as an argument and return a created status code if the new customer is added to the customer list or a bad request code if the customer already exists.</p><p>Before we get to the function, we need to update the warp import statement to allow the use of status codes.</p><p>In handlers.rs, change the line use warp; to the following:</p><pre>use warp::{self, http::StatusCode};</pre><p>This will allow the use of StatusCode enum as a response.</p><p>The function definition will be similar to the list_customers handler, so we can just jump into the full definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*bfnu_sZg4bXg1MgK.png" /></figure><h4>Get Customer</h4><p>The get_customer handler will take a guid and a data store reference as a parameter and returns a JSON object of the customer if it is found else it returns a default customer.</p><p>Before we write this implementation, we need to add one macro to the Customer struct. Update the Customer struct in models.rs to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*tIwigBAmb-Hy3eAy.png" /></figure><p>The function definition looks like this:</p><pre>pub async fn get_customer(guid: String, db: Db) -&gt; Result&lt;Box&lt;dyn warp::Reply&gt;, Infallible&gt; {<br>    <br>}</pre><p>The return type is a little different than the other functions. The reason is that we need to be able to return either a JSON object or a status code that indicates a not found error. Since warp::reply::json() and StatusCode implement the warp::Reply trait, we can use <a href="https://doc.rust-lang.org/1.8.0/book/trait-objects.html">dynamic dispatching</a> to return the appropriate type.</p><p>With the proper return type, our function body is fairly straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*96M88fxKgbAMTsLz.png" /></figure><p>The update_customer handler will take a customer and a data store reference as an argument and returns a status code of OK if the customer is found and updated or NOT FOUND if the customer is not in the data store.</p><p>The function should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*ROhNI2DEvwVwFpp6.png" /></figure><h4>Delete Customer</h4><p>The delete_customer handler will take a guid and a reference to the data store as an argument. The function will remove the customer with a matching guid and return a NO CONTENT status code. If a match is not found then it will return a NOT FOUND status code.</p><p>The function should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/0*ngz_PG8k5CD6L2C8.png" /></figure><h3>Routes</h3><p>We now have all the handler functions implemented. Next we need to piece together the routes that will call the handlers.</p><p>In main.rs, define another module:</p><pre>mod routes;</pre><p>Then we create a file called routes.rs in the src directory and add the following:</p><pre>use std::convert::Infallible;<br>use warp::{self, Filter};<br><br>use crate::db::Db;<br>use crate::handlers;<br>use crate::models::Customer;</pre><p>First we need a helper function to pass a reference of the data store into the handlers from the routes.</p><p>Add the following to routes.rs:</p><pre>fn with_db(db: Db) -&gt; impl Filter&lt;Extract = (Db,), Error = Infallible&gt; {<br>    warp::any().map(move || db.clone())<br>}</pre><p>This function allows the data store be injected into the route and passed along into the handler. Filter is a trait in the warp library. The Filter trait provides functionality to compose routes that are the result of one or more Filter methods. This will make more sense with an example.</p><p>Just for a reminder, here are the routes we need to define:</p><pre>/customers<br>    - GET -&gt; list all customers in data store<br>    - POST -&gt; create new customer and insert into data store<br>/customers/{guid}<br>    - GET -&gt; list info for a customer<br>    - POST -&gt; update information for a customer<br>    - DELETE -&gt; remove customer from data store</pre><h4>GET /customers</h4><p>The first route will simply get all customers in the data store. Add the following to the routes.rs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*hFQoRobNfeG2eIvh.png" /></figure><p>The function returns a type that implements the Filter trait. The Extract is used when a match occurs and the value of the Extract is returned.</p><p>Basically, the function is defining a route that matches when the requested path is “/customers” and it is a GET request.</p><p>Also, to save some work for later, I’ll implement another function that will serve as a wrapper for all the customer routes. It will make it easier later when we hook everything together.</p><p>So add the following to routes.rs:</p><pre>pub fn customer_routes(db: Db) -&gt; impl Filter&lt;Extract = impl warp::Reply, Error = warp::Rejection&gt; + Clone {<br>    customers_list(db.clone())<br>}</pre><h4>POST /customers</h4><p>This route will add a new customer to the data store if it doesn’t already exist.</p><p>One thing to add before we add the function for the route is a helper function to extract the JSON from the POST request body.</p><p>Add the following to routes.rs:</p><pre>fn json_body() -&gt; impl Filter&lt;Extract = (Customer,), Error = warp::Rejection&gt; + Clone {<br>    warp::body::content_length_limit(1024 * 16)<br>        .and(warp::body::json())<br>}</pre><p>The function will be very similar to customers_list except for the handler. Add the following to routes.rs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*QO6bpjm4AvFUeDwa.png" /></figure><p>This function defines a route the matches when the path is “/customers” and it is a post request. Then the JSON from the post request and the data store reference is extracted and passed in to the handler.</p><h4>GET /customers/{guid}</h4><p>This route will attempt to retrieve a single customer from the data store.</p><p>This route function will introduce the path! macro from warp. This macro enables us to create a path with a variable.</p><p>Add the following to routes.rs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*R700W6kAAIAS_sHR.png" /></figure><p>This defines a route the will match on “customers/{some string value} and a GET request. It then extracts the data store and passes it into the handler.</p><p>One thing to consider for routes is that the most specific route should be checked first otherwise a route may not be matched.</p><p>For example if the helper function for the routes is updated to this:</p><pre>pub fn customer_routes(<br>    db: Db,<br>) -&gt; impl Filter&lt;Extract = impl warp::Reply, Error = warp::Rejection&gt; + Clone {<br>    customers_list(db.clone())<br>        .or(create_customer(db.clone()))<br>        .or(get_customer(db.clone()))<br>}</pre><p>The get_customer route will never match because the share a common root path - &quot;/customers&quot; - which means the customer list route will match &quot;/customers&quot; and &quot;/customers/{guid}&quot;.</p><p>To fix the mismatch issue, arrange the route so the most specific match is first. Like this:</p><pre>pub fn customer_routes(<br>    db: Db,<br>) -&gt; impl Filter&lt;Extract = impl warp::Reply, Error = warp::Rejection&gt; + Clone {<br>    get_customer(db.clone())<br>        .or(customers_list(db.clone()))<br>        .or(create_customer(db.clone()))<br>}</pre><h4>PUT /customers/{guid}</h4><p>This route will attempt to update a customer if it exists and return an OK status code, otherwise a NOT FOUND status code is returned.</p><p>The route will look similar to the create customer route but it will match a different path. Add the following to routes.rs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*p4qZ4YEyFNYvPJqf.png" /></figure><p>Then update the customer route wrapper:</p><pre>pub fn customer_routes(<br>    db: Db,<br>) -&gt; impl Filter&lt;Extract = impl warp::Reply, Error = warp::Rejection&gt; + Clone {<br>    get_customer(db.clone())<br>        .or(update_customer(db.clone()))<br>        .or(create_customer(db.clone()))<br>        .or(customers_list(db))<br>}</pre><h4>DELETE /customers/{guid}</h4><p>The last route simply deletes a customer from the data store if it matches the given guid and then returns a NO CONTENT status code, otherwise a NOT FOUND status code is returned.</p><p>Add the following to routes.rs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*ihEuT6hZ44IwlHAV.png" /></figure><p>And then update the customer route wrapper. After all the routes have been added the wrapper should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*26Lt7FDRsebMAWXP.png" /></figure><p>This finishes up all the routes. Now we can move on to tying everything together.</p><h3>Main</h3><p>The main.rs will pull all of the pieces together. It will initialize the data store, get all the routes, and start the server. It&#39;s also fairly short file, so I&#39;ll just show the whole thing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*ll-s_yV799pUOgTA.png" /></figure><p>We’ve already seen the first few lines, so let’s go through the main function.</p><p>The function attribute #[tokio::main] sets the entry point for the tokio runtime. This allows us to declare the main function as async.</p><p>The first two lines of main are just calling functions from our modules. The first initializes the data store and the second gets our customer routes wrapper.</p><p>The last line uses warp::server to create a server and then run to start the server on the provided host and port. We use the await keyword to yield until the run function is finished.</p><h3>Review</h3><p>This completes a simple API using Rust and the Warp framework. The code base can be found <a href="https://github.com/andrewleverette/rust_warp_api">here</a>.</p><p>There are improvements that can be made however.</p><p>Here are a few ideas:</p><ul><li>Testing can be added to confirm that the endpoints are behaving as expected</li><li>Functionality can be added to the db module to allow for saving the data store by overwriting the JSON file.</li><li>The simple data store could be replaced with an actual database like PostgreSQL or even MongoDB.</li><li>Also, when the server is stopped using an interrupt signal from the command line, an error is thrown. This could be refactored to perform a graceful shutdown.</li></ul><p><em>Originally published at </em><a href="https://andrewleverette.github.io/warp-api/"><em>https://andrewleverette.github.io</em></a><em> on May 21, 2020.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*3N6R_9KQPVOHCiYG66Iytg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a52173860a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-an-api-using-warp-and-tokio-26a52173860a">Building an API using Toki and Warp</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>