Automating Python Function Conversion to FastAPI Endpoints

harshit-lyzr - Jun 24 - - Dev Community

In the rapidly evolving landscape of software development, APIs (Application Programming Interfaces) have become the backbone of modern applications, facilitating communication between different software components. FastAPI, a modern web framework for building APIs with Python, has gained popularity due to its high performance and ease of use. However, converting existing Python functions into FastAPI endpoints can be a tedious and error-prone process, especially for developers who are new to FastAPI.

Many developers and organizations have a significant amount of legacy code written in Python functions that need to be exposed as APIs. The manual conversion of these functions into FastAPI endpoints requires a deep understanding of both the existing codebase and the FastAPI framework. This process involves several steps, including error handling, input validation, and defining the correct API routes. Manual conversion is not only time-consuming but also prone to human errors, which can lead to bugs and security vulnerabilities in the API.

Objective
The objective is to develop a tool that automates the conversion of Python functions into FastAPI endpoints. This tool should:

Accept Python Function Code: Allow users to input their Python function code directly into the tool.
Validate and Compile Code: Automatically validate and compile the input code to ensure it is error-free.
Generate FastAPI Endpoints: Convert the validated Python function code into a fully functional FastAPI endpoint, handling aspects like request validation and response formatting.
Minimize User Effort: Provide a simple and intuitive interface that minimizes the effort required by the user to perform the conversion.
Ensure Code Quality: Maintain high standards of code quality and consistency in the generated FastAPI endpoints.
Solution
Leveraging the capabilities of Streamlit for the user interface and Lyzr Automata’s AI-Agents, the proposed solution will:

Input Python Function: Provide a text area for users to input their Python function code.
Process Code with AI: Use Lyzr Automata’s AI models to validate, compile, and convert the input code into a FastAPI endpoint.
Display Results: Show the generated FastAPI endpoint code to the user for review and use.

Setting Up the Environment
Imports:

Imports necessary libraries: streamlit, libraries from lyzr_automata

pip install lyzr_automata streamlit

Enter fullscreen mode Exit fullscreen mode
import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
Enter fullscreen mode Exit fullscreen mode

Sidebar Configuration
We create a sidebar for user inputs, including an API key input for accessing the OpenAI GPT-4 model. This ensures that the API key remains secure.

api = st.sidebar.text_input("Enter our OPENAI API KEY Here", type="password")

if api:
    openai_model = OpenAIModel(
        api_key=api,
        parameters={
            "model": "gpt-4-turbo-preview",
            "temperature": 0.2,
            "max_tokens": 1500,
        },
    )
else:
    st.sidebar.error("Please Enter Your OPENAI API KEY")
Enter fullscreen mode Exit fullscreen mode

Defining the Conversion Function
Now, let’s define a function that uses the Lyzr Automata model to convert the Python function into a FastAPI endpoint. We’ll use an agent and a task to accomplish this:

def fastapi_converter(code_snippet):
    python_agent = Agent(
        prompt_persona="You Are Expert Python developer who is expert in building fast api",
        role="Fast API Expert",
    )

    fastapi_task = Task(
        name="fast api converter",
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
        model=openai_model,
        agent=python_agent,
        log_output=True,
        instructions=f"""Your Are an Expert Python Developer. Your task is to convert the given code into Fast API.
        Follow these instructions:
        1. NLP check:
        Compile this code.
        If error:
            resolve the error
            return the resolved code
        else:
            return the entered code

        Convert the code into Fast API.
        2. Do not write anything apart from code.
        Code: {code_snippet}
        """,
    )

    output = LinearSyncPipeline(
        name="Generate FastAPI",
        completion_message="FastAPI Converted!",
        tasks=[fastapi_task],
    ).run()
    return output[0]['task_output']
Enter fullscreen mode Exit fullscreen mode

Output:

code = st.text_area("Enter Code", height=300)

if st.button("Convert"):
    solution = fastapi_converter(code)
    st.markdown(solution)
Enter fullscreen mode Exit fullscreen mode

Creates a text area for users to enter their Python code using st.text_area.
Defines a button using st.button titled "Convert".
When the button is clicked:
Calls the fastapi_converter function with the entered code.
Displays the converted FastAPI code using st.markdown.
Running the App
Finally, run the app using the following command in your terminal:

streamlit run app.py
try it now: https://lyzr-fastapi-converter.streamlit.app/

For more information explore the website: Lyzr[https://lyzr.ai/]

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .