Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Create a Rest API using FAST API (example without database connection)

Tiempo de lectura: 2 minutos

Reading time: 3 minutes

In this tutorial, I will show you how to create a REST API using FastAPI.

FastAPI is a modern and fast web framework for building APIs with Python 3.6+ based on the ASGI standard and with the philosophy of “less code, more productivity.” Additionally, FastAPI provides interactive and user-friendly automatic documentation, making it an excellent choice for creating APIs.

Before we begin, make sure you have Python 3.6+ installed on your system. Then, follow these steps:

Step 1: FastAPI Installation

To install FastAPI, simply run the following command in your terminal:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install fastapi uvicorn
pip install fastapi uvicorn
pip install fastapi uvicorn

uvicorn is an ASGI server used to run FastAPI applications.

Step 2: Creating the Application

Create a main.py file with the following content:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
from fastapi import FastAPI

app = FastAPI()

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

In the above code, we are creating an instance of FastAPI and defining a GET route at the root of the application (/) that returns a message “Hello World”.

Step 3: Running the Application

To run the application, simply execute the following command in your terminal:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
uvicorn main:app --reload
uvicorn main:app --reload
uvicorn main:app --reload

In this command, we are specifying the main.py file and the application instance app for uvicorn to run the application on http://localhost:8000. The --reload option allows the server to automatically restart whenever a code change occurs.

Step 4: Testing the Application

To test the application, simply visit http://localhost:8000 in your browser. You should see the message “Hello World” on the page.

You can also use a tool like Postman to make a GET request to http://localhost:8000 and receive the response.

Customizing the Route

If you want to customize the API route, simply change the parameter in the @app.get() decorator as shown below:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

In this example, we are defining a route /items/{item_id} that accepts a path parameter item_id and an optional query parameter q. The read_item function returns a dictionary with the values item_id and q.

Usage Example

You can use this template to create your own GET routes in FastAPI. Here’s an additional example that returns a list of items:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
from typing import Optional from fastapi import FastAPI app = FastAPI() fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] @app.get("/items/") async def read_item(skip: int = 0, limit: int = 10): return fake_items_db[skip : skip + limit]
from typing import Optional

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

In this example, we are defining a route /items that accepts two optional query parameters: skip and limit. The read_item function returns a list of items from the fake_items_db database, using the skip and limit query parameters to paginate the results.

Conclusion

In this tutorial, you have learned how to create a basic REST API using FastAPI. You have created an application, defined a route, and customized the route to accept query and path parameters. Additionally, we have seen a complete example of how to use FastAPI to create a list of items.

FastAPI is a modern and fast web development framework that can help you build APIs.

0

Leave a Comment