openapi_nexus/generators/python/httpx/
emit_api.rs1use std::collections::{BTreeMap, HashSet};
8
9use crate::codegen::traits::file_writer::FileInfo;
10use crate::ir::types::{
11 IrOperation, IrParameter, IrPrimitive, IrRequestBody, IrResponse, IrSpec, IrTypeExpr,
12 ParameterLocation,
13};
14use heck::{ToPascalCase, ToSnakeCase};
15use sigil_stitch::code_block::CodeBlock;
16use sigil_stitch::lang::python::Python;
17use sigil_stitch::prelude::*;
18
19use super::emit_models::{api_type_name, future_annotations_header, is_object_schema};
20
21pub fn generate_api_files(ir: &IrSpec, header: &str) -> Result<Vec<FileInfo>, String> {
23 let by_tag = group_by_tag(&ir.operations);
24 let mut files = Vec::with_capacity(by_tag.len());
25 for (tag, ops) in &by_tag {
26 let stem = tag.to_snake_case();
27 let filename = format!("{stem}_api.py");
28 let body = emit_api_file(tag, ops, ir, header);
29 files.push(FileInfo::api(filename, body));
30 }
31 Ok(files)
32}
33
34fn group_by_tag(operations: &[IrOperation]) -> BTreeMap<String, Vec<&IrOperation>> {
35 let mut out: BTreeMap<String, Vec<&IrOperation>> = BTreeMap::new();
36 for op in operations {
37 let tags: Vec<String> = if op.tags.is_empty() {
38 vec!["default".to_string()]
39 } else {
40 op.tags.clone()
41 };
42 for tag in tags {
43 out.entry(tag).or_default().push(op);
44 }
45 }
46 out
47}
48
49fn emit_api_file(tag: &str, ops: &[&IrOperation], ir: &IrSpec, header: &str) -> String {
50 let class_name = format!("{}Api", tag.to_pascal_case());
51 let plans: Vec<OpPlan> = ops.iter().map(|op| plan_operation(op)).collect();
52
53 let client_type = TypeName::importable("..runtime.client", "Client");
54 let error_type = TypeName::importable("..runtime.errors", "ApiError");
55
56 let init_body = CodeBlock::of("self._client = client", ()).expect("static body");
58 let init = FunSpec::builder("__init__")
59 .add_param(ParameterSpec::of("self", TypeName::primitive("")))
60 .add_param(ParameterSpec::of("client", client_type))
61 .returns(TypeName::primitive("None"))
62 .body(init_body)
63 .build()
64 .expect("__init__ FunSpec builds");
65
66 let mut cls = TypeSpec::builder(&class_name, TypeKind::Class).add_method(init);
67
68 for plan in &plans {
69 cls = cls.add_method(build_api_method(plan, ir, &error_type));
70 }
71
72 let file = FileSpec::builder_with(&format!("{}_api.py", tag.to_snake_case()), Python::new())
73 .header(future_annotations_header())
74 .add_type(cls.build().expect("API TypeSpec builds"))
75 .build()
76 .expect("API FileSpec builds");
77
78 let body = file.render(120).unwrap_or_default();
79 let mut content = String::with_capacity(header.len() + body.len());
80 content.push_str(header);
81 content.push_str(&body);
82 content
83}
84
85fn build_api_method(plan: &OpPlan<'_>, ir: &IrSpec, error_type: &TypeName) -> FunSpec {
86 let mut fun = FunSpec::builder(&plan.method_name);
87
88 fun = fun.add_param(ParameterSpec::of("self", TypeName::primitive("")));
90
91 for p in &plan.path_params {
93 fun = fun.add_param(ParameterSpec::of(
94 &p.var_name,
95 api_type_name(&p.param.type_expr),
96 ));
97 }
98
99 let has_keyword_params =
101 !plan.query_params.is_empty() || !plan.header_params.is_empty() || plan.body.is_some();
102 if has_keyword_params {
103 fun = fun.add_param(ParameterSpec::of("*", TypeName::primitive("")));
104 }
105
106 for p in plan.query_params.iter().chain(&plan.header_params) {
108 if p.param.required {
109 fun = fun.add_param(ParameterSpec::of(
110 &p.var_name,
111 api_type_name(&p.param.type_expr),
112 ));
113 }
114 }
115
116 if let Some(b) = &plan.body {
118 let ty = api_type_name(&b.type_expr);
119 if b.required {
120 fun = fun.add_param(ParameterSpec::of(&b.var_name, ty));
121 } else {
122 fun = fun.add_param(
123 ParameterSpec::builder(&b.var_name, TypeName::optional(ty))
124 .default_value(CodeBlock::of("None", ()).expect("None"))
125 .build()
126 .expect("optional body param"),
127 );
128 }
129 }
130
131 for p in plan.query_params.iter().chain(&plan.header_params) {
133 if !p.param.required {
134 fun = fun.add_param(
135 ParameterSpec::builder(
136 &p.var_name,
137 TypeName::optional(api_type_name(&p.param.type_expr)),
138 )
139 .default_value(CodeBlock::of("None", ()).expect("None"))
140 .build()
141 .expect("optional param"),
142 );
143 }
144 }
145
146 let return_type = if plan.typed_responses.is_empty() {
148 TypeName::primitive("None")
149 } else {
150 api_type_name(&plan.typed_responses[0].type_expr)
151 };
152 fun = fun.returns(return_type);
153
154 if let Some(summary) = &plan.op.summary {
156 fun = fun.doc(&format!("{summary}."));
157 }
158
159 fun = fun.body(build_method_body(plan, ir, error_type));
161
162 fun.build().expect("API method FunSpec builds")
163}
164
165fn build_method_body(plan: &OpPlan<'_>, ir: &IrSpec, error_type: &TypeName) -> CodeBlock {
166 let mut cb = CodeBlock::builder();
167
168 let path_expr = if plan.path_params.is_empty() {
170 format!("\"{}\"", plan.op.path)
171 } else {
172 let mut path_template = plan.op.path.clone();
173 for p in &plan.path_params {
174 let placeholder = format!("{{{}}}", p.param.name);
175 let replacement = format!("{{{}}}", p.var_name);
176 path_template = path_template.replace(&placeholder, &replacement);
177 }
178 format!("f\"{}\"", path_template)
179 };
180 cb.add_statement(&format!("path = {path_expr}"), ());
181
182 let has_query = !plan.query_params.is_empty();
184 if has_query {
185 cb.add_statement("params: dict[str, str] = {}", ());
186 for p in &plan.query_params {
187 let stringify = render_stringify(&p.var_name, &p.param.type_expr);
188 if p.param.required {
189 cb.add_statement(&format!("params[\"{}\"] = {stringify}", p.param.name), ());
190 } else {
191 cb.add_statement(&format!("if {} is not None:%>", p.var_name), ());
192 cb.add_statement(&format!("params[\"{}\"] = {stringify}%<", p.param.name), ());
193 }
194 }
195 }
196
197 let has_headers = !plan.header_params.is_empty();
199 if has_headers {
200 cb.add_statement("headers: dict[str, str] = {}", ());
201 for p in &plan.header_params {
202 let stringify = render_stringify(&p.var_name, &p.param.type_expr);
203 if p.param.required {
204 cb.add_statement(&format!("headers[\"{}\"] = {stringify}", p.param.name), ());
205 } else {
206 cb.add_statement(&format!("if {} is not None:%>", p.var_name), ());
207 cb.add_statement(
208 &format!("headers[\"{}\"] = {stringify}%<", p.param.name),
209 (),
210 );
211 }
212 }
213 }
214
215 let body_expr = if let Some(b) = &plan.body {
217 if is_object_type(&b.type_expr, ir) {
218 if b.required {
219 format!("{}.to_dict()", b.var_name)
220 } else {
221 format!(
222 "{}.to_dict() if {} is not None else None",
223 b.var_name, b.var_name
224 )
225 }
226 } else {
227 b.var_name.clone()
228 }
229 } else {
230 String::new()
231 };
232
233 let mut request_args = vec![
235 format!("\"{}\"", plan.op.method.to_uppercase()),
236 "path".to_string(),
237 ];
238 if has_query {
239 request_args.push("params=params".to_string());
240 }
241 if plan.body.is_some() {
242 request_args.push(format!("json={body_expr}"));
243 }
244 if has_headers {
245 request_args.push("headers=headers".to_string());
246 }
247
248 cb.add_statement(
249 &format!(
250 "response = self._client.request({})",
251 request_args.join(", "),
252 ),
253 (),
254 );
255
256 cb.add_statement("if response.status_code >= 400:%>", ());
258 cb.add_statement(
259 "raise %T(response.status_code, response.reason_phrase, response.content)%<",
260 (error_type.clone(),),
261 );
262
263 if !plan.typed_responses.is_empty() {
265 let tr = &plan.typed_responses[0];
266 let parse_expr = render_response_parse(&tr.type_expr, ir);
267 cb.add_statement(&format!("return {parse_expr}"), ());
268 } else {
269 cb.add_statement("return None", ());
270 }
271
272 cb.build().expect("API method body builds")
273}
274
275fn render_stringify(var: &str, type_expr: &IrTypeExpr) -> String {
276 match type_expr {
277 IrTypeExpr::Primitive(
278 IrPrimitive::String
279 | IrPrimitive::Date
280 | IrPrimitive::DateTime
281 | IrPrimitive::Uuid
282 | IrPrimitive::StringWithFormat(_),
283 )
284 | IrTypeExpr::StringLiteral(_)
285 | IrTypeExpr::StringEnum(_)
286 | IrTypeExpr::Named(_) => format!("str({var})"),
287 IrTypeExpr::Primitive(IrPrimitive::Boolean) => format!("str({var}).lower()"),
288 IrTypeExpr::Primitive(
289 IrPrimitive::Integer
290 | IrPrimitive::IntegerWithFormat(_)
291 | IrPrimitive::Number
292 | IrPrimitive::NumberWithFormat(_),
293 ) => format!("str({var})"),
294 IrTypeExpr::Nullable(inner) => render_stringify(var, inner),
295 _ => format!("str({var})"),
296 }
297}
298
299fn render_response_parse(type_expr: &IrTypeExpr, ir: &IrSpec) -> String {
300 match type_expr {
301 IrTypeExpr::Named(name) => {
302 let py_name = name.to_pascal_case();
303 if is_object_schema(name, ir) {
304 format!("{py_name}.from_dict(response.json())")
305 } else {
306 "response.json() # type: ignore[return-value]".to_string()
307 }
308 }
309 IrTypeExpr::Array(inner) => {
310 if let IrTypeExpr::Named(name) = inner.as_ref()
311 && is_object_schema(name, ir)
312 {
313 let py_name = name.to_pascal_case();
314 return format!("[{py_name}.from_dict(item) for item in response.json()]");
315 }
316 "response.json() # type: ignore[return-value]".to_string()
317 }
318 IrTypeExpr::Primitive(IrPrimitive::String | IrPrimitive::StringWithFormat(_)) => {
319 "response.text".to_string()
320 }
321 _ => "response.json() # type: ignore[return-value]".to_string(),
322 }
323}
324
325fn is_object_type(type_expr: &IrTypeExpr, ir: &IrSpec) -> bool {
326 if let IrTypeExpr::Named(name) = type_expr {
327 return is_object_schema(name, ir);
328 }
329 false
330}
331
332struct OpPlan<'a> {
337 op: &'a IrOperation,
338 method_name: String,
339 path_params: Vec<ParamBinding<'a>>,
340 query_params: Vec<ParamBinding<'a>>,
341 header_params: Vec<ParamBinding<'a>>,
342 body: Option<BodyBinding>,
343 typed_responses: Vec<TypedResponse>,
344}
345
346struct ParamBinding<'a> {
347 param: &'a IrParameter,
348 var_name: String,
349}
350
351struct BodyBinding {
352 var_name: String,
353 type_expr: IrTypeExpr,
354 required: bool,
355}
356
357struct TypedResponse {
358 type_expr: IrTypeExpr,
359}
360
361fn plan_operation<'a>(op: &'a IrOperation) -> OpPlan<'a> {
362 let op_id = sanitize_operation_id(&op.operation_id, &op.method, &op.path);
363 let method_name = op_id.to_snake_case();
364
365 let mut used_names: HashSet<String> = HashSet::new();
366 used_names.insert("self".to_string());
367
368 let mut path_params = Vec::new();
369 let mut query_params = Vec::new();
370 let mut header_params = Vec::new();
371
372 for p in &op.parameters {
373 let var_name = unique_name(&python_param_name(&p.name), &mut used_names);
374 let binding = ParamBinding { param: p, var_name };
375 match p.location {
376 ParameterLocation::Path => path_params.push(binding),
377 ParameterLocation::Query => query_params.push(binding),
378 ParameterLocation::Header => header_params.push(binding),
379 ParameterLocation::Cookie => header_params.push(binding),
380 }
381 }
382
383 let body = op
384 .request_body
385 .as_ref()
386 .and_then(|b| plan_body(b, &mut used_names));
387
388 let typed_responses = op.responses.iter().filter_map(plan_response).collect();
389
390 OpPlan {
391 op,
392 method_name,
393 path_params,
394 query_params,
395 header_params,
396 body,
397 typed_responses,
398 }
399}
400
401fn plan_body(b: &IrRequestBody, used_names: &mut HashSet<String>) -> Option<BodyBinding> {
402 let t = pick_body_type(b)?;
403 let var_name = unique_name("body", used_names);
404 Some(BodyBinding {
405 var_name,
406 type_expr: t,
407 required: b.required,
408 })
409}
410
411fn plan_response(r: &IrResponse) -> Option<TypedResponse> {
412 let t = pick_response_type(r)?;
413 Some(TypedResponse { type_expr: t })
414}
415
416fn pick_body_type(body: &IrRequestBody) -> Option<IrTypeExpr> {
417 body.content
418 .get("application/json")
419 .cloned()
420 .or_else(|| body.content.values().next().cloned())
421}
422
423fn pick_response_type(r: &IrResponse) -> Option<IrTypeExpr> {
424 r.content
425 .get("application/json")
426 .cloned()
427 .or_else(|| r.content.values().next().cloned())
428}
429
430fn python_param_name(name: &str) -> String {
431 let snake = name.to_snake_case();
432 if snake.is_empty() {
433 return "param".to_string();
434 }
435 match snake.as_str() {
436 "and" | "as" | "assert" | "async" | "await" | "break" | "class" | "continue" | "def"
437 | "del" | "elif" | "else" | "except" | "finally" | "for" | "from" | "global" | "if"
438 | "import" | "in" | "is" | "lambda" | "nonlocal" | "not" | "or" | "pass" | "raise"
439 | "return" | "try" | "while" | "with" | "yield" | "type" | "self" => {
440 format!("{snake}_")
441 }
442 _ => snake,
443 }
444}
445
446fn unique_name(desired: &str, used: &mut HashSet<String>) -> String {
447 if used.insert(desired.to_string()) {
448 return desired.to_string();
449 }
450 for i in 2..=u32::MAX {
451 let candidate = format!("{desired}{i}");
452 if used.insert(candidate.clone()) {
453 return candidate;
454 }
455 }
456 unreachable!("name collision space exhausted")
457}
458
459fn sanitize_operation_id(op_id: &str, method: &str, path: &str) -> String {
460 if !op_id.is_empty() {
461 return op_id.to_string();
462 }
463 let path_part: String = path
464 .chars()
465 .map(|c| if c.is_alphanumeric() { c } else { '_' })
466 .collect();
467 format!("{method}_{path_part}")
468}