Learn How to Build APIs Step-by-Step with Python

FastAPI is one of the most loved Python frameworks for building APIs. It is beginner-friendly and highly efficient – two reasons why developers love it. What makes FastAPI stand out is its use of Python-type hints and its foundation on Pydantic. These make it super simple to define data models and schemas for requests and responses. In this blog, we tell you how to create your first API with Python step by step. From setting up your environment to building an API for a simple machine-learning app, we will cover everything.

What is FastAPI?

FastAPI is designed to be efficient, simple, and reliable. FastAPI is becoming a go-to choice for developing web apps and RESTful APIs. Here are some features of FastAPI that make it a top choice:

  • Faster performance than a lot of web frameworks
  • Production-ready
  • Easy to develop APIs
  • Avoid code redundancy 
  • Swagger UI to form API documentation
  • Easy testing
  • Support for GraphQL, Dependency Injection, Background Fetching 

Steps to Creating a REST API with FastAPI

FastAPI is a high-performing web framework for building APIs with Python 3.6 and above. Creating a REST API with FastAPI is simple. You need to follow a few steps for that. You set up HTTP endpoints and handle responses and requests using Python. We have made it easier through a details guide:

  1. Install Python 3 and PIP/PIP3

First, make sure you have Python 3 installed. Once you have Python, follow these steps to install FastAPI and Uvicorn (which serves as the server) using pip:

pip install fastapi

pip install uvicorn

2. Create Main.py File and Set Up FastAPI

Now, create a file called main.py. In this file, import FastAPI and create an instance of the app:

from fastapi import FastAPI

app = FastAPI()

3. Add a Simple GET Request Endpoint

Next, let us add a basic GET request endpoint that returns a simple message. This is done by defining a function that will handle the GET request:

@app.get(“/”)

def read_root():

    return {“Hello”: “World”}

So now, the main.py file will look like this:

from fastapi import FastAPI

app = FastAPI()

@app.get(“/”)

def first_example():

    ”’

    FastAPI Example: A simple GET endpoint

    ”’

    return {“GFG Example”: “FastAPI”}

4. Run the Server

Run this command to start the server:

uvicorn main:app –reload

Use this command to run the FastAPI application with auto-reloading enabled. Hence, changes you make to the code will automatically reflect on the server.

EducationNest offers comprehensive corporate training courses that cover A to Z of everything. They are the best choice for corporate training. You will find expert-designed courses on cybersecurity, machine learning, web development, soft skills, and more.

5. Access Swagger UI

Now, open your browser and navigate to the URL: http://localhost:8000/docs

This will open the Swagger UI. Here, you can interact with your API, see the available endpoints, and test them directly from the browser.

A man building APIs with Python while coding on a laptop.

6. Add More Endpoints

Now that you have a basic GET endpoint, you can next add more functionality. You can define additional HTTP methods. Here are commands that you use to add POST, DELETE, and PUT requests.

Example: POST Request

Use the @app.post decorator to add a POST endpoint. Here’s how to create an endpoint that accepts data via a POST request:

from pydantic import BaseModel

# Define a Pydantic model for the request body

class Item(BaseModel):

    name: str

    description: str = None

    price: float

    tax: float = None

@app.post(“/items/”)

def create_item(item: Item):

    return {“name”: item.name, “price”: item.price}

In this example:

  • We created an ‘Item’ class using Pydantic, which will help us define the structure of the request body.
  • The create_item function accepts a request body matching the ‘Item’ model and returns the name and price of the item.

Example: PUT Request

You can also use PUT requests to update existing resources. 

@app.put(“/items/{item_id}”)

def update_item(item_id: int, item: Item):

    return {“item_id”: item_id, “name”: item.name, “price”: item.price}

In this case:

We are updating an item based on its ID (passed in the URL) and receiving the updated item data in the request body.

Example: DELETE Request

You can use the DELETE method if you need to delete resources:

@app.delete(“/items/{item_id}”)

def delete_item(item_id: int):

    return {“message”: f”Item with ID {item_id} has been deleted.”}

This endpoint simply accepts the ID of the item to be deleted and returns a confirmation message.

7. Validate Data Using Pydantic

You can easily validate incoming request data with FastAPI using Pydantic models. For example, the ‘Item’ model automatically ensures that the data sent in the request body matches the expected structure. If the validation fails, FastAPI will automatically return an error message.

8. Handle Path and Query Parameters

You can also use path and query parameters to accept data from the URL.

Path Parameters:

@app.get(“/items/{item_id}”)

def get_item(item_id: int):

    return {“item_id”: item_id}

This is how to capture the item_id as a path parameter in the URL (e.g., /items/1).

Query Parameters:

@app.get(“/items/”)

def list_items(skip: int = 0, limit: int = 10):

    return {“skip”: skip, “limit”: limit}

Here we define two query parameters: ‘skip’ and ‘limit.’ These two can be used to paginate results. For example, a request like /items/?skip=0&limit=5 would return the first 5 items.

9. Testing and Documentation

FastAPI automatically generates interactive documentation for your API using Swagger UI, accessible at http://localhost:8000/docs

Additionally, FastAPI provides another documentation page in ReST format at http://localhost:8000/redoc

These tools make it easy to test your API endpoints directly from the browser.

Read More
Python Web Development Made Easy – 6 Proven Strategies

Top 16 Python Applications in the Real World

Types of Literals in Python: The Ultimate Guide

Conclusion

Creating a REST API with FastAPI is really simple. This blog talks about how to create GET, PUT, POST, and DELETE endpoints. We also covered using Pydantic models for request validation. FastAPI is a powerful and flexible tool for building APIs quickly. Its built-in support for data validation, automatic documentation, etc. makes it a go-to choice. Once you know the basics, you can build more complex APIs. You can explore advanced features like authentication, dependency injection, etc.

If you are searching for comprehensive corporate courses for your workforce, EducationNest is here for your rescue. Being a top corporate training provider in India, they offer expert-led courses on cybersecurity, soft skills, digital marketing, and much more.