How to Convert OpenAPI to Rust - Step by Step Guide
From an OpenAPI 3 or Swagger 2 file to Rust structs that serde_json can read responses into
Paste or upload the spec
Paste an OpenAPI 3 or Swagger 2.0 file in YAML or JSON. The converter looks at components/schemas (OpenAPI 3) or definitions (Swagger 2) and writes one Rust type per schema:
Example: a spec with two schemas
Pet and NewPet, with a description, a string enum and a camelCase key:
openapi: 3.0.3
info:
title: Pets
version: 1.0.0
paths: {}
components:
schemas:
Pet:
type: object
description: A pet in the store
required: [id, name]
properties:
id: { type: integer, format: int64 }
name: { type: string }
species: { type: string, enum: [dog, cat, guinea-pig] }
birthDate: { type: string, format: date }
NewPet:
type: object
required: [name]
properties:
name: { type: string }
species: { type: string }Read the generated types
Each schema becomes a Rust struct or enum with serde derives, and keys that aren't snake_case keep their original spelling through #[serde(rename)]:
integer follows its format (i32, i64) and is i64 without one; number is f64required, or marked nullable, is an Option$ref: '#/components/schemas/Pet' uses the Pet type, and a schema that contains itself is held in a BoxExample: the Rust code for the spec above
This is exactly what the converter writes for the Step 1 example with the default options:
// Rust types for the components/schemas of "Pets" 1.0.0.
// Save as api_client.rs and add `mod api_client;` to main.rs or lib.rs.
// Cargo.toml:
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"
// Read a response: let value: Pet = serde_json::from_str(&body)?;
use serde::{Deserialize, Serialize};
/// A pet in the store
#[derive(Debug, Serialize, Deserialize)]
pub struct Pet {
pub id: i64,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub species: Option<PetSpecies>,
#[serde(rename = "birthDate", skip_serializing_if = "Option::is_none")]
pub birth_date: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum PetSpecies {
#[serde(rename = "dog")]
Dog,
#[serde(rename = "cat")]
Cat,
#[serde(rename = "guinea-pig")]
GuineaPig,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NewPet {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub species: Option<String>,
}Add the file to your crate
Download the file (it is named after the Module Name field, api_client.rs by default), put it next to main.rs, add serde = { version = "1", features = ["derive"] } and serde_json = "1" to Cargo.toml, and read a response like this:
mod api_client;
use api_client::Pet;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let body = r#"{"id": 8901240544102066246, "name": "Rex", "species": "guinea-pig"}"#;
let pet: Pet = serde_json::from_str(body)?;
println!("{} {} {:?}", pet.id, pet.name, pet.species);
Ok(())
}Want to check the spec first? The OpenAPI Validator points out structural problems before you generate code.
What is OpenAPI to Rust Conversion?
An OpenAPI (or older Swagger) file describes the JSON an API sends and receives. Writing the matching Rust structs by hand means a lot of Options, renames and integer sizes to get right, and one i32 too small for a real ID makes every response fail to parse. Generating them from the spec keeps your code in step with the API contract.
The output is plain Rust you can read and edit: one struct per object schema, enums for string enums, doc comments carrying the descriptions, defaults and allowed values from the spec, and a short note at the top for anything that needs your attention.
Got a JSON Schema instead of a full spec? Try JSON Schema to Rust, or JSON to Rust if all you have is a sample response. Writing Go instead? OpenAPI to Go does the same for Go structs.
Frequently Asked Questions
Which OpenAPI versions and formats can I paste?
OpenAPI 3.0 and 3.1 and Swagger 2.0, as YAML or JSON. The schemas are read from components/schemas in OpenAPI 3 and from definitions in Swagger 2. Paths, parameters and inline request or response bodies are not turned into types; if you need one of those, move it into components/schemas and point at it with $ref.
How are OpenAPI types mapped to Rust?
string becomes String, boolean becomes bool, number becomes f64 (f32 when the format is float). An integer follows its format: int32 gives i32 and int64 gives i64, and an integer without a format is i64, so a long ID like 8901240544102066246 fits. When a limit or enum value is bigger than i64, the field becomes u64 (if it can never be negative) or i128. Arrays become Vec, an object with additionalProperties becomes a HashMap, and an object with its own properties becomes a struct named after its parent and field, such as OrderShippingAddress.
What happens to required, nullable and optional fields?
A field listed in required is a plain value. A field that is not required, or is marked nullable (x-nullable in Swagger 2, or a type list with "null" in OpenAPI 3.1), becomes Option<T>, which serde fills with None when the key is missing or null. Optional fields also get skip_serializing_if so they are left out when you write JSON back.
How are $ref, allOf, oneOf and enums handled?
A $ref to another schema in the same file uses that type. A schema that contains itself, directly or through another one, is held in a Box so the struct has a finite size. allOf is merged into one struct with every property and required field from its parts. oneOf and anyOf with more than one shape become serde_json::Value, with a Note, since a correct untagged enum depends on how the API tells the shapes apart. String enums become Rust enums with #[serde(rename)] where the variant name differs (InTransit for "in-transit"). Number enums stay numbers with the allowed values in a doc comment, because serde's derived enums can't read JSON numbers.
What do the options change?
Field Visibility switches between pub fields and private ones. Derive Traits picks the derive list: Debug, Clone, PartialEq, Eq, Default, Serialize and Deserialize. Eq is left out with a note when a field is a float, because floats only implement PartialEq, and Default adds #[default] to the first variant of each enum. Turning off both Serialize and Deserialize also drops the serde attributes. The module name is the name of the downloaded .rs file.
Are default and enum values copied exactly?
Yes. Defaults and allowed values go into doc comments exactly as they appear in the spec, so 8901240544102066246 keeps every digit, "00501" keeps its leading zeros and 14.50 keeps its trailing zero. Field names are snake_case and keep the original key in #[serde(rename)] when they differ, keywords get the raw form (r#type) and names like self become self_. Two keys that would end up with the same Rust name, like first-name and firstName, become first_name and first_name_2.
Is this a full API client generator?
No, it writes the data types only, with no HTTP code. For a client with one function per endpoint, the OpenAPI Generator rust target or progenitor are the usual choices. The types from this page suit you when you make the calls yourself with reqwest, ureq or anything else and just want structs that match the spec.
Is my spec uploaded anywhere?
No. The spec is read and converted in your browser and is not sent to our server. Nothing is kept either: a reload starts with an empty editor.
Related Tools
OpenAPI Validator
Validate OpenAPI 3.0 and Swagger 2.0 specifications online. Check required fields, paths, operations, schemas, and security schemes with instant error reporting.
JSON to OpenAPI
Generate OpenAPI/Swagger specifications from JSON examples. Infer data types and create complete API schemas automatically.
OpenAPI Fixer
Fix broken OpenAPI and Swagger specifications automatically, repair malformed paths, schemas, $ref references, and YAML syntax errors
OpenAPI to Go
Generate type-safe Go structs with JSON tags from OpenAPI 3.0 and Swagger 2.0 specifications.
OpenAPI to TypeScript
Convert OpenAPI 3.0 and Swagger 2.0 specifications to TypeScript interfaces and types. Auto-generate type-safe TypeScript from any OpenAPI schema.
OpenAPI to Markdown
Convert OpenAPI 3.0 and Swagger 2.0 specifications to readable Markdown API documentation. Generate endpoint tables, parameter docs, and schema references.