FastAPI Course for Beginners

3 min read 1 year ago
Published on Aug 05, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial is designed to guide you through the basics of building APIs using FastAPI, a modern web framework for Python. By the end of this guide, you will understand how to install FastAPI, create your first API, and implement various types of request handling, including path parameters, query parameters, and CRUD operations (Create, Read, Update, Delete).

Chapter 1: Installation and Creating Your First API

  1. Install FastAPI and uvicorn:

    • Open your command prompt or terminal.
    • Run the following command to install FastAPI:
      pip install fastapi
      
    • Also, install uvicorn, which is an ASGI server to run your application:
      pip install uvicorn
      
  2. Set Up Your Project:

    • Create a new directory for your project.
    • Inside that directory, create a Python file named my_api.py.
  3. Create Your First API:

    • Open my_api.py in your code editor and add the following code:
      from fastapi import FastAPI
      
      app = FastAPI()
      
      @app.get("/")
      def read_root():
          return {"message": "First data"}
      
    • Run the server using this command:
      uvicorn my_api:app --reload
      
    • Visit http://127.0.0.1:8000 in your browser to see the output.
  4. Access Automatic Documentation:

    • FastAPI provides automatic documentation. Go to http://127.0.0.1:8000/docs to view the Swagger UI.

Chapter 2: Path Parameters

  1. Define a Path Parameter:
    • Update your my_api.py to include a path parameter for fetching student data:
      from fastapi import FastAPI
      from typing import Dict
      
      app = FastAPI()
      students: Dict[int, Dict[str, str]] = {
          1: {"name": "John", "age": "17", "class": "11"},
          2: {"name": "Jane", "age": "16", "class": "10"}
      }
      
      @app.get("/students/{student_id}")
      def get_student(student_id: int):
          return students.get(student_id, {"error": "Student not found"})
      
    • Now you can fetch student data by accessing http://127.0.0.1:8000/students/1.

Chapter 3: Query Parameters

  1. Using Query Parameters:
    • Modify your API to support fetching students by name:
      @app.get("/students/")
      def get_student_by_name(name: str):
          for student in students.values():
              if student["name"].lower() == name.lower():
                  return student
          return {"error": "Student not found"}
      
    • Access it by visiting http://127.0.0.1:8000/students/?name=John.

Chapter 4: Combining Path and Query Parameters

  1. Combining Parameters:
    • You can define both path and query parameters together:
      @app.get("/students/{student_id}/details/")
      def get_student_details(student_id: int, name: str = None):
          student = students.get(student_id)
          if student and (name is None or student["name"].lower() == name.lower()):
              return student
          return {"error": "Student not found"}
      
    • Visit http://127.0.0.1:8000/students/1/details/?name=John.

Chapter 5: Request Body and the POST Method

  1. Creating a POST Endpoint:
    • Create an endpoint to add a new student:
      from fastapi import Body
      
      @app.post("/students/")
      def create_student(student: Dict[str, str] = Body(...)):
          student_id = len(students) + 1
          students[student_id] = student
          return {"student_id": student_id}
      
    • You can test this endpoint using tools like Postman or curl.

Chapter 6: PUT Method

  1. Updating Existing Data:
    • Add a PUT method to update student details:
      @app.put("/students/{student_id}")
      def update_student(student_id: int, student: Dict[str, str] = Body(...)):
          if student_id not in students:
              return {"error": "Student does not exist"}
          students[student_id].update(student)
          return students[student_id]
      

Chapter 7: DELETE Method

  1. Deleting Data:
    • Implement a DELETE method to remove a student:
      @app.delete("/students/{student_id}")
      def delete_student(student_id: int):
          if student_id in students:
              del students[student_id]
              return {"message": "Student deleted successfully"}
          return {"error": "Student does not exist"}
      

Conclusion

In this tutorial, you learned how to set up FastAPI, create your first API, and handle various request types and parameters. You now have the foundational skills to build more complex APIs. As next steps, consider exploring database integration with FastAPI or expanding your API with additional endpoints and data handling features.