Building API Endpoints with FastAPI | FastAPI Tutorial #1

Posted by


In this tutorial, we will learn how to create an API endpoint using FastAPI, a modern and fast web framework for building APIs with Python. FastAPI is based on standard Python type hints, which allows for easy integration with databases and other Python packages. FastAPI also provides validation and serialization of input and output data, making it a powerful and efficient tool for creating APIs.

To get started with FastAPI, you will need to have Python installed on your machine. If you do not already have Python installed, you can download it from the Python website (https://www.python.org/downloads/). Once you have Python installed, you can install FastAPI and the necessary dependencies by running the following command in your terminal:

pip install fastapi uvicorn

Now that we have FastAPI installed, let’s create a new Python file for our API endpoint. Open your favorite code editor and create a new file called main.py. In this file, we will define our FastAPI application and create a simple API endpoint that returns a JSON response.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

In this code snippet, we import the FastAPI class from the fastapi package and create a new instance of it called app. We then use the @app.get() decorator to define a GET endpoint at the root URL ("/"). The read_root() function is called when the endpoint is accessed, and it returns a simple JSON response with the key "Hello" and value "World".

To run our FastAPI application, we can use the uvicorn command-line tool. In your terminal, navigate to the directory where your main.py file is located, and run the following command:

uvicorn main:app --reload

This command tells uvicorn to run the main module (defined in the main.py file) and use the app object for handling HTTP requests. The --reload flag enables auto-reloading of the server when changes are made to the code.

Once the server is running, you can access your API endpoint in a web browser or using a tool like curl. Simply navigate to http://localhost:8000/ in your browser, and you should see the JSON response {"Hello": "World"} displayed on the page.

Congratulations! You have successfully created an API endpoint using FastAPI. In the next tutorial, we will explore more advanced features of FastAPI, such as request validation, response serialization, and database integration. Stay tuned for more exciting tutorials on FastAPI!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jagratsingh3664
30 days ago

man this is best tutorial i found on fast API in entirety of yt