Getting Started with FastAPI: A Beginner's Guide

Getting Started with FastAPI: A Beginner's Guide

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It's designed to be easy to use and learn, making it a great choice for beginners. In this article, we'll walk you through the basics of getting started with FastAPI, including installation, creating your first API, and some practical use cases.


First of all, what is an API?

An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. Think of it as a bridge that enables two applications to talk to each other and share data or functionality. APIs are used in various contexts, such as web development, mobile apps, and cloud services. They allow developers to access certain features or data of an application without needing to understand its internal workings.

For example, when you use a weather app on your phone, it likely communicates with a weather service's API to fetch the latest weather data and display it to you.

There are several popular frameworks for building APIs in Python. Here are some of the most common ones:

Each of these frameworks has its own strengths and use cases, so the best choice depends on your specific needs and preferences.


Why FastAPI?

Before we dive in, let's briefly discuss why FastAPI is a good choice:

  • Speed: FastAPI is one of the fastest Python frameworks available.
  • Ease of Use: It has a simple and intuitive design.
  • Documentation: Automatically generated and interactive API documentation.
  • Type Safety: Uses Python type hints to provide better code completion and error checking.

Prerequisites

To follow along with this guide, you should have:

  • Basic knowledge of Python programming.
  • Python 3.7 or higher installed on your computer.
  • A code editor (like VS Code, PyCharm, or even a simple text editor).


Step 1: Install Python

First, ensure you have Python 3.7 or higher installed on your machine. You can download the latest version of Python from the official website.


Step 2: Create a project directory

You can use the command below or create a folder manually. If you do that manually, open the folder in your code editor

mkdir my_first_api
cd my_first_api        

Step 3: Installation

First, you'll need to install FastAPI and an ASGI server called uvicorn to run your application. Open your terminal and run the following command:

pip install fastapi uvicorn        

Step 3: Creating Your First FastAPI Application

Let's create a simple FastAPI application. Inside your project directory (step 2) create a new file called main.py and add the following code:

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}        

Here's a breakdown of what this code does:

  • We import FastAPI from the fastapi module.
  • We create an instance of the FastAPI class.
  • We define two endpoints:The root endpoint (/) which returns a simple JSON response.An endpoint to get items by ID (/items/{item_id}) which takes an item ID and an optional query parameter q.

Step 4: Running Your Application

To run your FastAPI application, use the following command in your terminal:

uvicorn main:app --reload        

  • main:app: refers to the app instance from your main.py file

  • --reload: makes the server restart after code changes, which is useful during development.

Open your browser and navigate to https://127.0.0.1:8000. You should see the JSON response {"Hello": "World"}. ??


Step 5: Interactive API Documentation

One of the coolest features of FastAPI is its automatically generated interactive API documentation. You can access it by navigating to `https://127.0.0.1:8000/docs` for Swagger UI or `https://127.0.0.1:8000/redoc` for ReDoc.

Use Cases

Here are a few practical use cases for FastAPI:

  1. Building RESTful APIs: FastAPI is perfect for creating RESTful APIs quickly and efficiently.
  2. Data Validation: With Pydantic, FastAPI can validate request data automatically.
  3. Asynchronous Programming: FastAPI supports asynchronous programming, making it ideal for applications that require high performance and concurrency.

Some more examples

Example 1: Path Parameters

Path parameters allow you to capture values from the URL. Here's an example of how to use them:

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
def read_user(user_id: int):
    return {"user_id": user_id}
        

In this example, the user_id is captured from the URL and returned in the response.

Example 2: Query Parameters

Query parameters are optional parameters that can be added to the URL. Here's how to use them:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}
        

In this example, skip and limit are query parameters with default values. You can access this endpoint with URLs like https://127.0.0.1:8000/items/?skip=5&limit=20.

Example 3: Request Body

You can also send data in the body of a request. FastAPI makes it easy to handle JSON data:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

@app.post("/items/")
def create_item(item: Item):
    return item
        

In this example, we define an Item model using Pydantic. The create_item endpoint accepts an Item object in the request body and returns it.


Conclusion

FastAPI is a powerful and easy-to-use framework for building APIs with Python. With its speed, ease of use, and excellent documentation, it's a great choice for beginners and experienced developers alike. By following this guide, you should now have a basic understanding of how to create and run a FastAPI application. Happy coding!

要查看或添加评论,请登录

Guilherme Bueno Rodrigues的更多文章

  • FastAPI: Um Framework Moderno e Rápido para Constru??o de APIs

    FastAPI: Um Framework Moderno e Rápido para Constru??o de APIs

    FastAPI é um framework web moderno e rápido (de alto desempenho) para construir APIs com Python 3.7+ baseado em dicas…

  • Let's Dive into Modules vs. Packages in Python

    Let's Dive into Modules vs. Packages in Python

    Python is a versatile and powerful programming language, widely used for various applications ranging from web…

  • Compreendendo Módulos e Pacotes em Python

    Compreendendo Módulos e Pacotes em Python

    Python é uma linguagem de programa??o versátil e poderosa, amplamente utilizada para várias aplica??es, desde…

  • Aula 02 — Lógica de programa??o

    Aula 02 — Lógica de programa??o

    O que é lógica de programa??o? Lógica de programa??o nada mais é do que uma sequência de instru??es com o intuito de…

    3 条评论
  • Aula 01 - Introdu??o a programa??o

    Aula 01 - Introdu??o a programa??o

    O que é programa??o? Programa??o, de maneira bem simples, é o ato de escrever um determinado conjunto de instru??es…

    2 条评论
  • Iniciando em Python

    Iniciando em Python

    Python é uma linguagem poderosa capaz de permitir a cria??o de diversos tipos de ferramentas de maneira prática e…

    3 条评论

社区洞察

其他会员也浏览了