Sobes.tech
Middle

import fastapi import requests app = fastapi.FastAPI() @app.get() def get_posts(first_n, custom_ids: list = []): ids = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] posts = [None for i in range(first_n)] i = 0 for post_id in (custom_ids or ids[:first_n]): url = f"[link] response = requests.get(url, verify=False) posts[i] = response.json() return posts

sobes.tech AI

Answer from AI

The provided code has several issues and inaccuracies:

  1. The @app.get() decorator requires a path, for example @app.get("/posts").
  2. Function parameters should be annotated with types and, if possible, with default values for FastAPI.
  3. The parameter custom_ids: list = [] is better replaced with custom_ids: Optional[List[int]] = None to avoid mutable default arguments.
  4. In the loop, (custom_ids or ids[:first_n]) is used, but if custom_ids is an empty list, it will be ignored, which may be non-obvious.
  5. Indentation in the code is broken; return posts should be inside the function.
  6. Requests to external URLs are performed synchronously, which can slow down the API.

Here's an example of a corrected version using FastAPI and asynchronous requests with httpx:

from fastapi import FastAPI, Query
from typing import List, Optional
import httpx

app = FastAPI()

ids = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

@app.get("/posts")
async def get_posts(first_n: int = 5, custom_ids: Optional[List[int]] = Query(None)):
    selected_ids = custom_ids if custom_ids else ids[:first_n]
    posts = []
    async with httpx.AsyncClient(verify=False) as client:
        for post_id in selected_ids:
            url = f"https://example.com/posts/{post_id}"
            response = await client.get(url)
            posts.append(response.json())
    return posts

This approach improves readability, correctly handles parameters, and increases performance through asynchronous requests.