Open In App

Creating First REST API with FastAPI

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we’ll walk you through the steps to create your very first REST API using FastAPI. By the end, you’ll have a solid foundation for building and deploying APIs with ease.

What is FastAPI?

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. FastAPI has gained popularity due to its simplicity, automatic documentation generation, and excellent performance.

Features of FastAPI :

  • High Performance than many Web Frameworks, faster than Node.js, etc.
  • Easy to Develop APIs
  • Production Ready
  • Well Documentation to learn code fast
  • Swagger UI to form API Documentation
  • Avoid Redundancy of Code
  • Easy Testing
  • Support for GraphQL, Background Fetching, Dependency Injection

CREATING REST API USING FastAPI

Creating a REST API with FastAPI involves defining endpoints for different HTTP method GET and handling requests and responses using Python functions. Below, I’ll provide a step-by-step guide to creating a simple REST API using FastAPI.

Now,Install Python 3 and pip/pip3 according to your Operating System:

pip install fastapi

Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :

pip install uvicorn

Now create a main.py file and import fastapi, also create a server

Python3




from fastapi import FastAPI
app = FastAPI()


Now, let’s add the code for sample get request as shown below :

Python3




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


Hence, the main.py file will look like :

Python3




from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def first_example():
  '''
     FG Example First Fast API Example
  '''
      return {"GFG Example": "FastAPI"}


Now, start the server using

uvicorn main:app --reload

Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docs You will be able to see the Swagger UI Home page as below : Swagger UI

Expand the “First Example” : REST API with FastAPI

Now try to Execute the API, you will get the success status with 200 code . The Response will be {“GFG Example”: “FastAPI”} as shown below :

FastAPI

and like this if you want to create the all the type of

CRUD operation in FAST API

Create an item in Fast API

Creating an item in FastAPI involves defining a data model for the item, creating an API endpoint to handle POST requests to create the item, and setting up the database to store the item.

Create a post Api to create Item in main.py file.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

# In-memory database (for demonstration purposes)
items = []

# Pydantic model for item data
class Item(BaseModel):
    name: str
    description: str

# Create an item
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    items.append(item)
    return item

This will create a method to post an item in fast API and with interactive screen provided by FAST Api and start the sever

uvicorn main:app --reload     

create-1

Creating post API in fast API

and when we click on the excute button our API will get executed and get the output as shown in the picture.

create-2

get API response

Get an item in Fast API

To retrieve (GET) an item in FastAPI, you need to create an API endpoint that handles GET requests for a specific item. Here’s how you can do it step by step

As we created an item above using post API now to get that item we can create an get API to get the item and add the code to the above code

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    if item_id < 0 or item_id >= len(items):
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]
get-1

get method in FAST API

and when we click on the excute button our API will get executed and get the output as shown in the picture.

get-2

Response of the get API

Update an item in Fast API

To update (PUT) an item in FastAPI, you need to create an API endpoint that handles PUT requests to modify an existing item.

Import the required modules and set up your FastAPI app, including the database configuration (assuming you have already defined the Item model and database session as shown in previous examples

Add the below code the main.py to create a put API with Fast API

# Update an item
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
    if item_id < 0 or item_id >= len(items):
        raise HTTPException(status_code=404, detail="Item not found")
    
    items[item_id] = item
    return item

Now we update the name of the item from ABHISHEK SHKAYA to ABHISHEK SHAKYA-NEW and hit execute and the API will update the item name from ABHISHEK SHKAKYA to ABHISHEK SHAKYA-NEW and we get the output as shown.

PUT-2

response of the update API in fast API

Delete an item in Fast API

To delete an item in FastAPI, you need to create an API endpoint that handles DELETE requests for a specific item.

Import the required modules and set up your FastAPI app, including the database configuration (assuming you have already defined the Item model and database session as shown in previous examples

Add the below code to the main.py to delete the item from the model in FAST API

# Delete an item
@app.delete("/items/{item_id}", response_model=Item)
async def delete_item(item_id: int):
    if item_id < 0 or item_id >= len(items):
        raise HTTPException(status_code=404, detail="Item not found")
    
    deleted_item = items.pop(item_id)
    return deleted_item

pass the id of the item you want to delete in my case which is 0.

Delete-1

Delete API i fast API

and when we click on the excute button our API will get executed and give the output as shown in the picture.

delete-2

Response of Delete API in fast API



Similar Reads

Install Fastapi And Run Your First Fastapi Server On Windows
FastAPI is a modern, fast web framework for building APIs with Python 3.7+ based on standard Python-type hints. In this article, we'll walk through the process of installing FastAPI and creating a simple FastAPI server on a Windows system. Pre-Requisite: PythonFastAPIInstall And Run Python Fastapi Server On WindowsBelow is the step-by-step procedur
2 min read
FastAPI - FastAPI Event Handlers
A Python framework that is used for building APIs is called FastAPI. There are some circumstances when the user needs to identify a certain event that happened in the API. This can be done using event handlers in FastAPI. In this article, we will study the various event handlers available in FastAPI. What is Event Handler in FastAPI?In FastAPI, an
3 min read
FastAPI - Rest Architecture
FastAPI is a modern web framework for building APIs with Python. When developing a RESTful API with FastAPI, you can follow a REST architectural style, which stands for Representational State Transfer. In this article, we will learn about the FastAPI-Rest Architecture. Before going let's understand the following concepts: FastAPI is a modern, fast
9 min read
Making HTTP Requests from a FastAPI Application to an External API
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. Your FastAPI server may need to fetch data from other external APIs, to perform da
4 min read
Creating and Using Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization,
3 min read
Browsable API in Django REST Framework
The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header. It helps us to use web browsers to surf through the API and can make di
8 min read
Python | Build a REST API using Flask
Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework f
3 min read
How to Create a basic API using Django Rest Framework ?
Django REST Framework is a wrapper over the default Django Framework, basically used to create APIs of various kinds. There are three stages before creating an API through the REST framework, Converting a Model's data to JSON/XML format (Serialization), Rendering this data to the view, and Creating a URL for mapping to the views.This article revolv
4 min read
How to automatically create API Documentation in Django REST Framework?
Prerequisite - https://www.geeksforgeeks.org/how-to-create-an-app-in-django/ Writing documentation can be pretty daunting for developers and to be honest, nobody likes writing long explanations, I personally don't but as we all know, documentation is equally important as writing a properly functioning code. So, there is a pretty simple way of autom
3 min read
Adding Permission in API - Django REST Framework
There are many different scenarios to consider when it comes to access control. Allowing unauthorized access to risky operations or restricted areas results in a massive vulnerability. This highlights the importance of adding permissions in APIs. Django REST framework allows us to leverage permissions to define what can be accessed and what actions
7 min read
Article Tags :
Practice Tags :