FastAPI: A Step-by-Step Guide to Creating Your First API

Posted by

FastAPI is a modern and fast web framework for building APIs with Python 3.7+. It provides a simple and intuitive way to create high-performance APIs using asynchronous programming, type checking, and automatic validation.

To create your first API with FastAPI, you’ll need to have Python 3.7 or higher installed on your machine. Once you have Python installed, you can create a new directory for your project and open a terminal or command prompt in that directory. From there, you can create a new virtual environment using the following command:

“`html
python3 -m venv venv
“`

After creating the virtual environment, you can activate it by running the following command:

“`html
source venv/bin/activate
“`

Once your virtual environment is activated, you can install FastAPI and an ASGI server using the following command:

“`html
pip install fastapi uvicorn
“`

Now that you have FastAPI installed, you can create your first API by creating a new Python file (e.g., main.py) in your project directory. In this file, you can define your API using FastAPI’s intuitive syntax. For example:

“`html
from fastapi import FastAPI

app = FastAPI()

@app.get(“/”)
def read_root():
return {“Hello”: “World”}
“`

In this example, we’ve created a simple API that responds with a JSON object containing a “Hello” message when a GET request is made to the root endpoint (“/”).

To run your API, you can use the uvicorn command-line interface, which comes with FastAPI. In the terminal, run the following command:

“`html
uvicorn main:app –reload
“`

This command tells uvicorn to run the main.py file and use the app variable as the FastAPI app. The –reload flag enables auto-reloading, so your server will automatically restart whenever you make changes to your code.

Once your API is running, you can open a web browser and navigate to http://127.0.0.1:8000/ to see your API in action. You should see a JSON response with the “Hello” message that we defined earlier.

That’s it! You’ve just created your first API with FastAPI. FastAPI’s simple syntax and excellent performance make it a great choice for building APIs with Python. Whether you’re building a small personal project or a large-scale production application, FastAPI can help you create robust and efficient APIs with ease.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ingridgott
10 months ago

que buen video gracias por la información

@jjen9595
10 months ago

Video para que no olvidarte del inglés 😅