<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jordi Oltra on Medium]]></title>
        <description><![CDATA[Stories by Jordi Oltra on Medium]]></description>
        <link>https://medium.com/@jordioltra2?source=rss-dfa7deb3dddf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AkX0Cczm-Uv6tsnwKNyLWg.png</url>
            <title>Stories by Jordi Oltra on Medium</title>
            <link>https://medium.com/@jordioltra2?source=rss-dfa7deb3dddf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:11:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jordioltra2/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MLflow, Quick Start Guide]]></title>
            <link>https://medium.com/@jordioltra2/mlflow-quick-start-guide-b556fff4e218?source=rss-dfa7deb3dddf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b556fff4e218</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jordi Oltra]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 08:29:33 GMT</pubDate>
            <atom:updated>2024-03-11T16:17:37.242Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Storing and utilizing a basic scikit-learn model locally with MLflow.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*OsB57V0FPteixDBD_BBN4g.png" /><figcaption>MlFlow logo</figcaption></figure><h3>Content</h3><ol><li><em>Introduction to MlFlow.</em></li><li><em>Architecture.</em></li><li><em>Start and log your first model.</em></li><li><em>Improve performance with Optuna.</em></li><li><em>Compare model performance.</em></li><li><em>Deploy the best model.</em></li></ol><h3><em>Introduction to MlFlow</em></h3><p>As a data scientist, have you ever trained a bunch of ML or deep learning models and found it challenging to track the model performance?</p><p>Let me guess: are you naming your model with the experiment name, the choosen metric and the epoch?</p><p>If you are facing this issue, I can offer you a solution that I use on a daily basis.</p><p>You may want to have a look at MlFlow. MLflow is an open-source platform designed to help manage end-to-end machine learning models lifecycle. It was developed by Databricks and has gained popularity in the machine learning community. MLflow provides a unified interface for tracking experiments, packaging code into reproducible runs, and sharing and developing models.</p><p>MLflow is a fundamental tool for aspiring data scientists aiming for greatness. It facilitates seamless communication with the MLOps team. With MLflow, you can ensure that your models are consistently stored in the same folder. Additionally, you gain the ability to alternate various libraries such as Torch, Keras, scikit-learn, and more.</p><p>With MLflow, deploying models onto different platforms such as SageMaker, Triton Server, FastAPI, Docker, and others will be straightforward for you.</p><p>This ease of deployment is made possible by its architecture.</p><h3>Architecture</h3><p>In terms of architecture, it is as flexible as any user could demand. You may deploy MLflow wherever you prefer: GCP, AWS, Azure, Kubernetes cluster, and several other instances. You only requirements are the following:</p><ol><li><strong>Relational database</strong>: to store metadata.</li><li><strong>Storage</strong>: in order to store models and required files.</li><li><strong>Tracking server</strong>: to allocate the UI which connects the relational database (RDB) with your storage.</li></ol><p>With these three main components that comprise MLflow architecture, you can delve into the various built-in options they provide.</p><p><a href="https://mlflow.org/docs/latest/tracking.html">MLflow Tracking</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUJQTQ3rY2Sm4QGUd6PVpg.png" /><figcaption>Different ways of deploying. See:(<a href="https://mlflow.org/docs/latest/tracking.html">https://mlflow.org/docs/latest/tracking.html</a>)</figcaption></figure><h3>Start and log your first model</h3><p>In this tutorial we are going to use the default architecture.</p><p>First, you will need to install Mlflow.</p><pre>pip install mlflow</pre><p>Once MLflow is installed, Note that the current achitecture will be deployed in your current path, as the entire MLflow architecture will be deployed there.</p><pre>mlflow server --host 127.0.0.1 --port 8080</pre><p>Now, you should be able to see your MlFlow UI on the URL: <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CztAVrI-xgMe0SQvbhhPqw.png" /><figcaption>MlFlow UI</figcaption></figure><p>You may follow the entire process in this <a href="https://github.com/20rd1/End2End-model-deployment/blob/main/house-price-prediction.ipynb">notebook</a>. From reading the data to logging the model in MLflow. In order to run the notebook, you may use this dataset stored in <a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/data">Kaggle</a>.</p><h4>Train your ML model</h4><p>In this tutorial, we are focusing on logging scikit-learn models. However, this tutorial is generic, and you can follow it without worrying about your machine learning or deep learning framework. I’ll let you know if anything changes for any library. Additionally, another story will be published on training and deploying a deep learning model using MLflow.</p><p>You may use the following code in case you need to train a model:</p><pre># Import sklearn library<br>from sklearn.linear_model import Ridge<br><br><br># Define parameters<br>params = {<br>    &quot;alpha&quot;: 1.0,<br>    &quot;fit_intercept&quot;: True,<br>    &quot;solver&quot;: &quot;auto&quot;,<br>}<br><br># Instantiate the Ridge model with parameters<br>ridge = Ridge(**params)<br><br># Train the model<br>ridge.fit(X_train, y_train)<br><br># Predict<br>predictions = ridge.predict(X_test)<br><br># Evaluate your model<br>mae, mse, rmse, r_squared = evaluation(y_test, predictions)<br></pre><h4>Register the model in MlFlow</h4><p>This is the standard path you would follow in order to train a simple model. Now, we are going to register this model into MLflow. In beginning, it might sound confusing, but it is as simple as adding a couple of lines.</p><p>First, you have to set up your MlFlow environment.</p><pre># Import the library<br>import mlflow<br><br># Connect to the MLflow server (in this case, we are using our own computer)<br>mlflow.set_tracking_uri(uri=&quot;http://localhost:8080&quot;)<br><br># Set the tracking experiment (in this case, House Prices is going to be our experiment name)<br>mlflow.set_experiment(&quot;House Prices&quot;)</pre><p>Once the model is trained, you can log all the model and the model’s information through different functions like:</p><pre># Start an MLflow run<br>with mlflow.start_run(run_name=run_name):<br>  <br>  ####### The format has to be json #######<br>  &#39;&#39;&#39; Selected data can be uploaded at the same time&#39;&#39;&#39;<br>  <br>  # Log the hyperparameters<br>  mlflow.log_params(params)<br>  <br>  # Log the loss metric<br>  mlflow.log_metrics(metric_eval)<br>  <br>  <br>  ####### The format has to be int or float #######<br>  &#39;&#39;&#39; Selected data can be uploaded one by one&#39;&#39;&#39;<br>  <br>  # Log a hyperparameter<br>  mlflow.log_param(&quot;lr&quot;, 0.001)<br>  <br>  # Log a loss metric<br>  mlflow.log_metric(&quot;val_loss&quot;, val_loss)<br>  <br>  <br>  ####### Log the model #######<br>  <br>  # Infer the model signature<br>  signature = infer_signature(X_train, model.predict(X_train))<br>  <br>  # Log the model<br>  model_info = mlflow.sklearn.log_model( # Depends on the framework -&gt; mlflow.pytorch, mlflow.spark...<br>      sk_model=model,<br>      artifact_path=&quot;hose-price&quot;,<br>      signature=signature,<br>      input_example=X_train,<br>  )<br>  <br>  <br>  # Set a tag that we can use to remind ourselves what this run was for<br>  mlflow.set_tag(&quot;Training Info&quot;, &quot;Basic Ridge model for house prices&quot;)</pre><p>You might leverage where or how to store your data. Each method has advantages and disadvantages, I usually use ‘log_params’. However, I use ‘log_metric’ when I want to update the metrics in an epoch, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWtPxEPJzOjp64o97IEDaQ.png" /><figcaption>Models logged in MlFlow</figcaption></figure><p>By clicking on the model’s name, its details will be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJHKhaIqZWrtRMJE3garMg.png" /><figcaption>Model information overview</figcaption></figure><p>If you want to activate the model system metrics, you might add this line of code in your Jupyter notebook.</p><pre>mlflow.enable_system_metrics_logging()</pre><p><a href="https://mlflow.org/docs/latest/system-metrics/index.html">System Metrics — MLflow 2.11.0 documentation</a></p><p>Another important thing to note is that you have the option to enrich all this information by incorporating images with the model details, tables, etc.</p><pre>################ log image ######################<br><br># Read the image file back into a variable<br>correlation_matrix_image = Image.open(&#39;correlation_matrix.png&#39;)<br><br># Log the correlation matrix image as an artifact<br>mlflow.log_image(correlation_matrix_image, &quot;correlation_matrix.png&quot;)<br><br><br>############### log dataset #####################<br><br>dataset_train = mlflow.data.from_pandas(X_train, &quot;training_data&quot;)<br>mlflow.log_input(dataset_train, context=&quot;training&quot;)</pre><p>After registering all the information, on the artifacts tab, you might find all the information that a ML engineer needs to deploy the model: requirements, inputs, outputs, the model itself, small tutorials, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lipIZzLMBEEulD5tl_MzWQ.png" /><figcaption>Model information</figcaption></figure><h3><em>Improve performance with Optuna</em></h3><p>Once we know how to log a model on MLflow, it’s time to introduce Optuna.</p><p>Optuna is an open-source hyperparameter optimization framework that streamlines the process of tuning machine learning models. It automates the search for the best set of hyperparameters by using various optimization algorithms, making it efficient and user-friendly. With Optuna, users can easily define their search spaces, specify objective functions, and let the framework handle the optimization process. It supports both traditional and state-of-the-art optimization algorithms, enabling researchers and practitioners to achieve better model performance with minimal effort.</p><p>In summary, Optuna is a library that helps us find the best model for solving our problem by testing different hyperparameters of the model.</p><p>Optuna has to has 2 main things:</p><ol><li>A function to optimize.</li><li>Hyperparameters to be tested.</li></ol><h4>Function</h4><p>Function we are going to optimize is our model, so we are going to create a Python function in which we will include the model training and logging in MLflow.</p><pre>def register_model_mlflow(run_name, params, model, X_train, X_test, y_train, y_test):<br>    &quot;&quot;&quot;<br>    Registers a trained machine learning model and its associated artifacts with MLflow.<br><br>    Parameters:<br>        run_name (str): Name of the MLflow run.<br>        params (dict): Hyperparameters used for training the model.<br>        model (sklearn.base.BaseEstimator): Trained machine learning model.<br>        X_train (pandas.DataFrame): Features of the training dataset.<br>        X_test (pandas.DataFrame): Features of the testing dataset.<br>        y_train (pandas.Series): Target variable	<br>	 of the training dataset.<br>        y_test (pandas.Series): Target variable of the testing dataset.<br><br>    Returns:<br>        tuple: Trained model instance and evaluation metrics.<br><br>    &quot;&quot;&quot;<br>    with mlflow.start_run(run_name=run_name):<br>        # Instantiate the model with specified hyperparameters<br>        model_instance = model(**params)<br>        model_instance.fit(X_train, y_train)<br>        predictions = model_instance.predict(X_test)<br><br>        # Evaluate the model<br>        mae, mse, rmse, r_squared = evaluation(y_test, predictions)<br><br>        # Log predictions as a table<br>        prediction_table = X_test.copy()<br>        prediction_table[&quot;ground_truth&quot;] = y_test<br>        prediction_table[&quot;predictions&quot;] = predictions<br>        mlflow.log_table(data=prediction_table, artifact_file=&quot;predictions.csv&quot;)<br><br>        # Log evaluation metrics<br>        metric_eval = {&quot;MAE&quot;: mae, &quot;MSE&quot;: mse, &quot;RMSE&quot;: rmse, &quot;R2 Score&quot;: r_squared}<br>        mlflow.log_metrics(metric_eval)<br><br>        # Log hyperparameters<br>        mlflow.log_params(params)<br><br>        # Set a tag to describe the training<br>        mlflow.set_tag(&quot;Training Info&quot;, &quot;Basic Ridge model for house prices&quot;)<br><br>        # Log the trained model<br>        signature = infer_signature(X_train, model_instance.predict(X_train))<br>        model_artifact_path = &quot;ridge_model&quot;<br>        mlflow.sklearn.log_model(<br>            sk_model=model_instance,<br>            artifact_path=model_artifact_path,<br>            signature=signature,<br>            input_example=X_train,<br>        )<br><br>        # Log an image as an artifact<br>        correlation_matrix_image = Image.open(&#39;correlation_matrix.png&#39;)<br>        mlflow.log_image(correlation_matrix_image, &quot;correlation_matrix.png&quot;)<br><br>        # Log the datasets<br>        train_dataset = mlflow.data.from_pandas(X_train, &quot;training_data&quot;)<br>        mlflow.log_input(train_dataset, context=&quot;training&quot;)<br>        test_dataset = mlflow.data.from_pandas(X_test, &quot;test_data&quot;)<br>        mlflow.log_input(test_dataset, context=&quot;test&quot;)<br><br>        return model_instance, metric_eval</pre><h4>Hyperparameters to be tested</h4><p>In this step, we need to define another function. Within this function, we will access the suggested hyperparameters and their respective ranges for Optuna to test. Upon completing the trial, we must provide Optuna with the metric or metrics we aim to optimize.</p><pre>def objective(trial):<br>    &quot;&quot;&quot;<br>    Objective function for hyperparameter optimization.<br><br>    Args:<br>        trial (optuna.trial.Trial): A single optimization trial.<br><br>    Returns:<br>        float: Root mean squared error (RMSE) metric for the Ridge regression model.<br>    &quot;&quot;&quot;<br>    # Define hyperparameters to be optimized<br>    params = {<br>        &quot;alpha&quot;: trial.suggest_float(&#39;alpha&#39;, 1e-10, 1, log=True),<br>        &quot;fit_intercept&quot;: trial.suggest_categorical(&#39;fit_intercept&#39;, [True, False]),<br>        &quot;solver&quot;: trial.suggest_categorical(&#39;solver&#39;, [&#39;auto&#39;, &#39;svd&#39;, &#39;cholesky&#39;, &#39;lsqr&#39;, &#39;sparse_cg&#39;, &#39;sag&#39;, &#39;saga&#39;])<br>    }<br><br>    # Generate a unique identifier for the run<br>    new_uuid = uuid.uuid4()<br><br>    # Register the model and evaluate its performance<br>    model, metric_eval = register_model_mlflow(f&quot;Ridge_{new_uuid}&quot;, params, Ridge, X_train, X_test, y_train, y_test)<br><br>    # Select the metric to be maximized (RMSE)<br>    rmse = metric_eval[&quot;RMSE&quot;]<br><br>    return rmse</pre><p>Last but not least, we need to evaluate.</p><pre># Create a study object and optimize the objective function.<br>study = optuna.create_study(direction=&#39;minimize&#39;) # Minimaize or maximize, depends on the metric<br>study.optimize(objective, n_trials=50) # You have to specify how much trials you want to test</pre><h3><em>Compare model performance</em></h3><p>In this case, we only need to compare a single metric; however, the process remains the same if you want to compare multiple metrics simultaneously. Here, we will explore two different methods of comparing model metrics, but it’s important to note that you can optimize this process using code.</p><ul><li>The first and fastest method is to sort the models by the metric of your choice.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5cZ7oPjFbvNAPzgVBDqog.png" /><figcaption>Sort metrics</figcaption></figure><ul><li>The second is clicking on the chart.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex2kBSf5LwvjPbtG4JqoEg.png" /><figcaption>Evaluate performance</figcaption></figure><h3><em>Deploy the best model</em></h3><p>When you believe you have found the optimal model for your task, you simply need to register it. Registering a model informs the system that you intend to use this specific model in the future. Let’s proceed with registering a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMVmGQHYbWzz1HH9nDi3xg.png" /><figcaption>Register the model selected</figcaption></figure><p>At the top right of your screen, you will find a blue button labeled ‘Register Model’. Then you just have to provide the generic name it will have. Alternatively, you can create a new version within an existing one.</p><h4>Tab models</h4><p>In this tab, you will find all the significant models that you believe could help solve your problem at a specific point in time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y21uo0GeKc12eJ3S_eufMw.png" /><figcaption>Model versioning</figcaption></figure><p>In my case, the name of my model is ‘tracking-quickstart’ and it has 12 versions.</p><p>An important aspect you should consider is this button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*aN_Z_GuzeNYmEn_sllIukg.png" /></figure><p>This button only changes the way you tag your model versions. For example, in the old version, we tagged the models with 3 stages. With these tags, you know which model to use and what to evaluate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*EqHJztnPFA-IWaGOpZiOhw.png" /></figure><p>Meanwhile, with the new version, you can decide how many tags to use and their purpose.</p><h4>Use the model</h4><p>MLflow offers various methods for deploying models. Here, I’ll demonstrate one approach using Python.</p><pre>import mlflow<br>import mlflow.pytorch<br>from mlflow.models.signature import infer_signature<br>from mlflow.tracking import MlflowClient<br><br># Set the MLflow tracking URI<br>mlflow.set_tracking_uri(&quot;http://localhost:8080&quot;)<br><br># Specify the experiment name<br>EXPERIMENT_NAME = &quot;House Prices&quot;<br>mlflow.set_experiment(EXPERIMENT_NAME)<br><br># Initialize the MLflow client<br>client = MlflowClient()<br><br># Name of the model to be used<br>MODEL_NAME = &#39;tracking-quickstart&#39;<br><br># Search for the latest version of the model in the model registry<br>max_version = 0<br>for mv in client.search_model_versions(f&quot;name=&#39;{MODEL_NAME}&#39;&quot;):<br>    current_stage = dict(mv)[&#39;aliases&#39;]<br>    if current_stage == [&#39;champion&#39;]: # champion is the tag we selected for deploy the model<br>        model_deploy = mv<br><br># Download the model<br>model = mlflow.sklearn.load_model(model_deploy.source, dst_path=None)<br><br># Use the model<br>model.predict(X_test[:1])</pre><p>Thank you for reading this story, I hope it will help you in your future projects.</p><p>If you would like to test any MLops tool, just let me know, and I’ll write about it. Alternatively, I would be happy to collaborate with you :)</p><p>See you soon, best wishes.</p><h3>References</h3><p><a href="https://mlflow.org/">MLflow - Open Source AI Platform for Agents, LLMs &amp; Models</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b556fff4e218" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic FastAPI good practices]]></title>
            <link>https://medium.com/@jordioltra2/basic-fastapi-good-practices-b44a923b4f89?source=rss-dfa7deb3dddf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b44a923b4f89</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Jordi Oltra]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 13:56:31 GMT</pubDate>
            <atom:updated>2023-12-03T13:56:31.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>Content</h3><ol><li><em>Introduction to FastAPI</em></li><li><em>First steps</em></li><li><em>Path Operations</em></li><li><em>Pydantic with validations</em></li><li>Final test</li><li>Next steps</li></ol><h4>Introduction to FastAPI</h4><p>FastAPI is a powerful and hight-performance Python web framework designed for bilding APIs quickly and efficiently. FastAPI offers incredible speed and scalability, making it a prefered choice for building robust web applications.</p><p>With its performance, asynchronous support, automatic API documentation generation, and built-in request validation, FastAPI has gained popularity among developers.</p><blockquote>In this article, you will learn how to implement a basic API schema that you can use when creating a new API project. The topic of this API is movies but you can change the topic and the methodology. If you want to see the full code you can check my <a href="https://github.com/20rd1/Basic-api">github repository</a>.</blockquote><h4><strong>First steps</strong></h4><p>Before starting to code, you need to understand what a method is and identify the primary methods used in creating an API. The main methods you can use when developing an API are:</p><ul><li><strong>POST: </strong>Create a new resource.</li><li><strong>PUT: </strong>Modify an existing resource.</li><li><strong>GET: </strong>Retrieve information about a resource.</li><li><strong>DELETE: </strong>Delete a resource.</li></ul><p>Once we have these methods clear, we will move on to creating a “Hello world” with the framework.</p><p>First of all, installing the requirements:</p><pre>pip install fastapi<br>pip install uvicorn</pre><p>Next, you will need to introduce the file main.py</p><pre># Import fastapi libraries <br>from fastapi import FastAPI<br>from fastapi.responses import HTMLResponse<br><br># Assign API, API title and version<br>app = FastAPI()<br>app.title = &quot;Basic API with FastAPI&quot;<br>app.version = &quot;0.0.1&quot;<br><br># Create a GET method that responds with HTML code<br>@app.get(&#39;/&#39;, tags = [&#39;home&#39;])<br>def message():<br>    return HTMLResponse(&#39;&lt;h1&gt;Hello world&lt;/h1&gt;&#39;)</pre><ol><li>app.get(&#39;/&#39;): This is a decorator that defines a route for handling HTTP GET requests at the root URL (&#39;/&#39;). In FastAPI, the @app.get decorator is used to define a route for handling GET requests.</li><li>tags=[&#39;home&#39;]: This is an optional parameter that specifies the tags associated with this route. Tags are used for organizing and documenting routes. In this case, the route is tagged with &#39;home&#39;. Example: Image 1.</li><li>def message():: This is the function that will be executed when a GET request is made to the specified URL. It is named &#39;message&#39; in this case.</li><li>return HTMLResponse(&#39;&lt;h1&gt;Hello world&lt;/h1&gt;&#39;): This line returns an HTML response with the content &#39;&lt;h1&gt;Hello world&lt;/h1&gt;&#39;. The HTMLResponse is likely an instance of a class or function provided by the FastAPI framework to handle HTML responses.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7jA_jjFP9ti9VB3wNIoVg.png" /><figcaption>Image 1: Example of tags</figcaption></figure><p>Next step is runnig the main file. For running the file is needed run it with the server uvicorn.</p><pre>uvicorn main:app</pre><p>The filename is typically named ‘main.py,’ and in this file, we define a FastAPI instance using the variable name ‘app’ with the syntax app = FastAPI(). This allows us to create multiple APIs within a single Python file.</p><p>If you open your browser and navigate to the path ‘<a href="http://localhost:8000/">http://localhost:8000</a>,&#39; you will see the message ‘Hello, world!’ displayed on your screen.</p><p>An additional impressive feature of FastAPI is that it includes Swagger UI by default. You can explore the API documentation by visiting ‘<a href="http://localhost:8000/docs">http://localhost:8000/docs</a>. <strong>It is remarkable that you will be able to try every API call we develop in this article through this documentation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jxv7ntctfG4wuMDrll2Qtw.png" /><figcaption>Image2: Swagger documentation</figcaption></figure><h4><strong>Path operations</strong></h4><p>In this section of the article, we will explore the creation of new methods and delve into the utilization of both <strong>path parameters</strong> and <strong>query parameters</strong>. In the earlier introduction, we employed the GET method. Having established a foundation with this method, I will now elaborate on the concepts of <strong>path parameters</strong> and <strong>query parameters</strong>.</p><p>For the next examples you will need a variable “movies”. This is an example you can use:</p><pre>movies = [<br>    {<br>        &#39;id&#39;: 1,<br>        &#39;title&#39;: &#39;Avatar&#39;,<br>        &#39;overview&#39;: &quot;On a lush planet called Pandora, the Na&#39;vi live, beings that...&quot;,<br>        &#39;year&#39;: &#39;2009&#39;,<br>        &#39;rating&#39;: 7.8,<br>        &#39;category&#39;: &#39;action&#39;    <br>    },{<br>        &#39;id&#39;: 2,<br>        &#39;title&#39;: &#39;Avatar&#39;,<br>        &#39;overview&#39;: &quot;On a lush planet called Pandora, the Na&#39;vi live, beings that...&quot;,<br>        &#39;year&#39;: &#39;2009&#39;,<br>        &#39;rating&#39;: 7.8,<br>        &#39;category&#39;: &#39;action&#39;    <br>    } <br><br>]</pre><p><strong>Path parameters</strong></p><pre>@app.get(&#39;/movies/{id}&#39;, tags=[&#39;movies&#39;])<br>def get_movie(id: int):<br>    for item in movies:<br>        if item[&quot;id&quot;] == id:<br>            return item<br>    return []</pre><p>We can observe a difference compared to the previous call. The new API endpoint is at the path /movies/{id}. To make this API call, you need to enter the following path in your browser: http://localhost:8000/movies/, followed by the ID of the movie for which you want to retrieve information. For example, you can access information for two movies using the paths <a href="http://localhost:8000/movies/1">http://localhost:8000/movies/1</a> and <a href="http://localhost:8000/movies/2">http://localhost:8000/movies/2</a>.</p><p>It’s important to note that if you input an ID that is not present in the JSON example, the response will be an empty array [].</p><p><strong>Query parameters</strong></p><pre>@app.get(&#39;/movies/&#39;, tags=[&#39;movies&#39;])<br>def get_movies_by_category(category: str):<br>    data = [movie for movie in movies if movie[&#39;category&#39;] ==category]<br>    return JSONResponse(content=data)</pre><p>In the provided FastAPI example, there is an endpoint for getting movies based on a specified category. The @app.get(&#39;/movies/&#39;, tags=[&#39;movies&#39;]) decorator indicates that this is a GET request for the /movies/ path.</p><p>The function get_movies_by_category takes a single parameter category of type str. This category parameter is a path parameter, not a query parameter. In this case, it is part of the URL path, and it is used to filter movies based on the specified category.</p><p>Here’s how you might use this API endpoint:</p><p>Assuming you are running your FastAPI server locally at http://localhost:8000, you can get movies of a specific category by appending the category to the URL. For example:</p><ul><li><a href="http://localhost:8000/movies/?category=action">http://localhost:8000/movies/?category=action</a></li></ul><p>In this example, action is a query parameter, and it&#39;s used to filter movies by the specified category. The FastAPI framework automatically maps the category parameter from the URL to the function&#39;s category parameter.</p><p>So, in the example function, it retrieves movies where the category matches the specified value (action in this case) and returns them in the response. This is a simple way to use path and query parameters to customize the behavior of your API endpoint.</p><p><strong>Post method</strong></p><p>A POST method is an HTTP request used to submit data to a server for processing. It is commonly employed to create new resources on the server, and the data is included in the body of the request rather than in the URL. The POST method is often used for actions with side effects, such as creating, updating, or deleting resources.</p><p>In the following example, we will add new data to the movies variable using a JSON structure. To specify that we expect specific information in the JSON payload, we&#39;ll utilize the Body() function. The Body() function is employed to declare that the parameters should be extracted from the request body. FastAPI automatically recognizes types and extracts data from the request body by default. It&#39;s noteworthy that FastAPI generates a JSON Schema for the request automatically, and the Body() function facilitates this process.</p><pre>@app.post(&#39;/movies&#39;, tags=[&#39;movies&#39;])<br>def create_movie(id: int = Body(), title: str = Body(), overview: str = Body(), year: int = Body(),rating: float = Body(), category: str = Body()):<br>    json_movie = {<br>        &#39;id&#39;: id,<br>        &#39;title&#39;: title,<br>        &#39;overview&#39;: overview,<br>        &#39;year&#39;: year,<br>        &#39;rating&#39;: rating,<br>        &#39;category&#39;: category    <br>    } <br>    movies.append(json_movie)<br>    return movies</pre><p><strong>Put Method</strong></p><p>The PUT method in HTTP is used to update or create a resource on a server. It involves sending data in the request body to modify the state of an existing resource or create a new one.</p><p>In the next example, we are going to create an API endpoint to update the records within the variable movies.</p><pre>@ app.put(&#39;/movies/{id}&#39;, tags=[&#39;movies&#39;])<br>def update_movie(id: int, title: str = Body(), overview: str = Body(), year: int = Body(),rating: float = Body(), category: str = Body()):<br>    for item in movies:<br>        if item[&quot;id&quot;] == id:<br>            item[&#39;title&#39;] = title<br>            item[&#39;overview&#39;] = overview<br>            item[&#39;year&#39;] = year<br>            item[&#39;rating&#39;] = rating<br>            item[&#39;category&#39;] = category<br>    return movies</pre><p><strong>Delete Method</strong></p><p>The DELETE method in HTTP is used to request the removal or deletion of a specified resource on a server. It is often employed to eliminate an existing resource based on its unique identifier, such as an ID or URL.</p><p>In the next example, we are going to create an API call for deleting movie records by specifying the film’s ID.</p><pre>@app.delete(&#39;/movies/{id}&#39;, tags=[&#39;movies&#39;])<br>def delete_movie(id: int):<br>    for item in movies:<br>        if item[&quot;id&quot;] == id:<br>            movies.remove(item)<br>            return movies</pre><h4><em>Pydantic with validations</em></h4><p>At this time, if you observe, the parameters we are using to introduce data into the API are specified in each function when we define them. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*IvZbUPL0VDftWOcyzdJmuw.png" /></figure><p>In this case, we are specifying that we will need an integer value to delete a record. Furthermore, in other functions, we are specifying six variables. If we develop an API with a lot of calls, it will be a pain.</p><p><strong>How can we centralize variables needed for every API call?</strong></p><h4><em>Pydantic with validations</em></h4><p>The library we can use for managing the data we will need in different parts of our API is Pydantic. First you have to import the library in your main file.</p><pre>from pydantic import BaseModel, Field<br>from typing import Optional</pre><p>In our case, we are going to create a data schema. To do this, we will create a class Movie that inherits the BaseModel function included in the Pydantic library.</p><p>Here, we import the necessary components from Pydantic to kickstart our data schema.</p><pre>class Movie(BaseModel):<br>    id: Optional[int] = None<br>    title: str = Field(min_length=5, max_length=15)<br>    overview : str = Field(min_length=15, max_length=50)<br>    year: int = Field(le=2022)<br>    rating: float = Field(ge=0,  le=10)<br>    category: str = Field(min_length=3, max_length=15)</pre><p>The Movie class is our data schema, inheriting from Pydantic&#39;s BaseModel. Each attribute of the class represents a property of a movie, such as id, title, overview, year, rating, and category. Pydantic&#39;s Field class is used to apply constraints to these attributes, ensuring that the data adheres to specific rules.</p><ul><li>id: An optional integer field, defaulting to None.</li><li>title: A string field with a minimum length of 5 characters and a maximum length of 15 characters.</li><li>overview: A string field with a minimum length of 15 characters and a maximum length of 50 characters.</li><li>year: An integer field with a maximum value of 2022.</li><li>rating: A floating-point field with a minimum value of 0 and a maximum value of 10.</li><li>category: A string field with a minimum length of 3 characters and a maximum length of 15 characters.</li></ul><pre>class Movie(BaseModel):<br>    id: Optional[int] = None<br>    title: str = Field(min_length=5, max_length=15)<br>    overview : str = Field(min_length=15, max_length=50)<br>    year: int = Field(le=2022)<br>    rating: float = Field(ge=0,  le=10)<br>    category: str = Field(min_length=3, max_length=15)<br><br>    model_config = {<br>     &quot;json_schema_extra&quot;: {<br>            &quot;examples&quot;: [<br>                {<br>                    &quot;id&quot;: 1,<br>                    &quot;title&quot;: &quot;Mi Pelicula&quot;,<br>                    &quot;overview&quot;: &quot;Descripcion de la pelicula&quot;,<br>                    &quot;year&quot;: 2022,<br>                    &quot;rating&quot;: 9.9,<br>                    &quot;category&quot;: &quot;Acción&quot;<br>                }<br>            ]<br>        }<br>    }</pre><p>In this section, we define a model_config attribute to store additional configuration options. The json_schema_extra key provides extra metadata for JSON Schema generation. The &quot;examples&quot; section includes a sample movie object, showcasing how the data should be structured.</p><p>By leveraging Pydantic’s capabilities, we not only enforce data integrity but also generate documentation that aids both developers and API consumers. This data schema serves as a robust foundation for handling movie-related information in our API, promoting consistency and reliability.</p><p>As an example, you can find it in Swagger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*IMCPT_3ZWwwmJQ2SKH-e_g.png" /><figcaption>Image 3: example in Swagger</figcaption></figure><p>Now, we are going to use our data schema in one of our API calls:</p><pre>@ app.put(&#39;/movies/{id}&#39;, tags=[&#39;movies&#39;], response_model=dict, status_code=200)<br>def update_movie(id: int, movie: Movie) -&gt; dict:<br>    for item in movies:<br>        if item[&quot;id&quot;] == id:<br>            item[&#39;title&#39;] = movie.title<br>            item[&#39;overview&#39;] = movie.overview<br>            item[&#39;year&#39;] = movie.year<br>            item[&#39;rating&#39;] = movie.rating<br>            item[&#39;category&#39;] = movie.category<br>    return JSONResponse(status_code=200, content={&quot;message&quot;: &quot;Se ha modificado la pelicula&quot;})</pre><p>As you can see what you need to do for request the data in the class Movie,is declare a variable which contain a json with all the information. It then updates the movie’s attributes (title, overview, year, rating, category) with the values from the incoming movie object.</p><h4><strong>Final test</strong></h4><p>I recommend testing each step in Swagger on <a href="http://localhost:8000/docs">localhost:8000/docs</a> in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyuSxXUGqDAvpn2uoMQw7w.png" /><figcaption>Image 4: Swagger view.</figcaption></figure><p>If you choose any of these calls, you will see different information: the details you need to share with the API for it to work, the ability to try it out, and last but not least, the possible responses with examples that the API may return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbJNYNevIPZyvPUjUoPc7g.png" /><figcaption>Image 5: Try an API call</figcaption></figure><p>If you want to try the API call, you only need to click the ‘Try it out’ button and enter the required information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xyjn6YMGHo6M5YcLYTUbtA.png" /><figcaption>Image 6: Try a GET call</figcaption></figure><p>After executing the call, you will see the Swagger API call being made and the corresponding response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dF0h3LDCUwrOHDgCO1Ngzg.png" /></figure><h4>Next steps</h4><p>Thank you for reading my first story on Medium. I hope you enjoyed it, and I hope it proves to be useful for you.</p><p>While the story provides a basic introduction to FastAPI and Swagger, there’s so much more to explore if you aspire to become proficient in creating APIs. Dive into the following resources to elevate your skills and master the art of API development:</p><ol><li>HTTP responses</li><li>API security measures</li><li>Connect with databases</li></ol><h4>References:</h4><ul><li><a href="https://blog.hubspot.com/website/api-calls">API Calls: What They Are &amp; How to Make Them in 5 Easy Steps</a></li><li><a href="https://http.dev/status">HTTP Status Codes</a></li></ul><p><a href="https://platzi.com/cursos/fastapi/">https://platzi.com/cursos/fastapi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b44a923b4f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>