Web Services: Outgoing with JSON, XML, & CSV
Master data export formats in Ruby on Rails
Data Export Formats Covered
JSON
JavaScript Object Notation for modern web APIs. Lightweight and widely supported across programming languages.
XML
Extensible Markup Language for legacy systems. Structured format compatible with older content management systems.
CSV
Comma-Separated Values for data analysis. Perfect for spreadsheet applications and accounting departments.
In your code editor, open nutty > app > controllers > products_controller.rb
We'll modify the existing index action to support JSON responses. This leverages Rails' built-in content negotiation system, allowing the same controller action to serve different formats based on the request.
Starting around line 7, add the following code to enable multi-format responses:
def index
@get_nutty = true
@products = Product.all
respond_to do |format|
format.html
format.json { render json: @products }
end
end
NOTE: The respond_to helper is a powerful Rails feature that enables content negotiation. This pattern allows your API to serve both human-readable HTML and machine-readable JSON from the same endpoint—a hallmark of RESTful design.
Save the file and keep it open for further modifications.
In your browser, navigate to the standard products page: localhost:3000/products
This displays the familiar HTML interface your users see.
Now access the JSON API endpoint: localhost:3000/products.json
You should see a JSON feed containing all product information from the previous step. This endpoint can now be consumed by any application capable of making HTTP requests—mobile apps, partner websites, or internal analytics tools.
Let's test the API programmatically. In Terminal, start the Rails console:
rails cExecute an HTTP request against your own API:
r = HTTParty.get('http://localhost:3000/products.json')
This demonstrates how external services would interact with your API.
Explore the returned data with these console commands:
r.count
r.first['title']
You should receive the total number of products (8) and the title of the first product (Tinfoil Hat).
While this works perfectly for Ruby on Rails applications, there's a significant security consideration: we're exposing all product data. In a production environment, you might have sensitive information like wholesale costs, profit margins, or internal notes that shouldn't be public.
Let's implement proper data filtering. Return to products_controller.rb in your code editor.
Modify the JSON response to include only specific fields:
format.json { render json: @products, only: [:title, :sku, :price] }
This approach follows the principle of least privilege—exposing only the data necessary for partners to function.
Save the file and test your changes.
Refresh the API endpoint in your browser: localhost:3000/products.json
The response now contains only the title, SKU, and price for each product—much cleaner and more secure for public consumption.
Adding Partner-Friendly Data
Create Model Method
Add partner_link method to Product model using the friendly URL slug
Include in API Response
Use methods parameter in render json to include computed values alongside database fields
JSON vs XML Implementation
| Feature | JSON | XML |
|---|---|---|
| Syntax | render json: @products | render xml: @products.as_json |
| Processing | Direct rendering | Convert to JSON first |
| File Extension | .json | .xml |
If you encounter authentication issues, try this alternative approach:
Once logged in, click the Orders link in the navigation.
Notice the download links below the order listing—Active Admin automatically provides CSV, XML, and JSON export functionality.
Click the CSV download link to export the data.
Open the downloaded file in Excel or your preferred spreadsheet application if it doesn't open automatically.
The default export provides basic information, but accounting departments typically need more comprehensive data. We could modify the index page display, but that would affect the web interface. Instead, let's create a custom CSV export configuration.
In your code editor, open nutty > app > admin > order.rb
Remove any commented-out placeholder code to start with a clean configuration.
Add a comprehensive CSV export configuration:
ActiveAdmin.register Order do
csv do
column :id
column :email
column :total
column("Products") { |o| o.products.collect(&:title).join(", ") }
column("Order Date") { |o| o.created_at.strftime("%-m/%-d/%Y %-I:%M%p") }
end
end
This configuration creates a business-friendly export with order ID, customer email, total amount, product list, and formatted order date. The custom date formatting converts Rails' default military time to a more readable format that accounting teams expect.
Save the configuration file.
Test the enhanced export by reloading: localhost:3000/admin/orders.csv (or return to the Orders page and click the CSV download link)
Your custom export now provides comprehensive order information ready for accounting analysis, financial reporting, and business intelligence applications.
Keep Terminal, your code editor, and browser open—we'll continue building upon this foundation in the next exercise.
Key Takeaways