How to Build a FastAPI CRUD API with JWT

1.4M views
•
February 15, 2021
by
Sarthaksavvy
YouTube video player
How to Build a FastAPI CRUD API with JWT

TL;DR

Build a FastAPI blog API by installing FastAPI in a Python virtual environment, defining routes and Pydantic schemas, connecting SQLAlchemy, and implementing CRUD operations. Complete the application with password hashing, user and blog relationships, JWT bearer authentication, protected routes, Swagger and ReDoc documentation, structured routers and repositories, exception handling, response models, and deployment through deta.sh.

Transcript

hello and welcome to the fast api course this fast api is a super fast python web framework there are other frameworks like django or flask or maybe other but fast api is very very modern and it has a very nice feature of a synchronous programming which is still lacking in django framework so let's see how this fast api is going to make your life e... Read More

Key Insights

  • FastAPI is a modern Python web framework focused on building APIs, with asynchronous programming identified as one of its important features. The course contrasts this API-centered design with Django and Flask, which the description characterizes as frameworks that also focus on serving files.
  • Automatic documentation is built into FastAPI through Swagger UI and ReDoc. Swagger displays created routes, permits requests to be tried directly, shows responses, and supports authentication, while ReDoc presents the same API documentation through a more minimal interface.
  • FastAPI uses Python type hints and the Pydantic library to define expected values, such as string user identifiers or integer IDs. This typing system also enables autocomplete in editors including VS Code and PyCharm, helping developers write and inspect application code.
  • FastAPI is based on OpenAPI and JSON Schema, which gives the application a standardized API structure and JSON communication format. The course presents these foundations as a way to create APIs according to established conventions used by modern applications.
  • FastAPI is built over Starlette, bringing support for WebSockets, GraphQL, background tasks, and startup and shutdown events into FastAPI applications. The framework also supports SQL databases, NoSQL databases, dependency injection, plugins, and application testing through a system that uses pytest.
  • The course project is a blog API with database-backed create, read, update, and delete operations. SQLAlchemy is used to connect to the database, define models, create tables, store blogs, retrieve records, delete entries, and establish a two-way relationship between users and blogs.
  • Response models are used to control which fields an API returns. This is especially important for user records because the application should expose only approved information and must prevent sensitive fields, including stored passwords, from appearing in API responses.
  • JWT authentication works by verifying login credentials, returning an access token with the bearer type, and placing selected routes behind authentication. Requests without valid authentication receive a 401 unauthorized response, while authenticated requests can access protected blog endpoints and creator relationship data.

Explore YouTube Video Summarizer or Get YouTube Transcript Extractor

Questions & Answers

Q: How do you start a FastAPI project in Python?

Start with Python version 3.6 or later, then create a virtual environment using Python's venv module. Activate the environment with the appropriate command for the operating system, such as sourcing its bin/activate file on macOS. Install the framework inside that environment with pip3 install fastapi. This keeps the FastAPI installation associated with the project environment rather than requiring a global installation.

Q: What automatic API documentation does FastAPI provide?

FastAPI automatically provides Swagger UI and ReDoc documentation for created API endpoints. Swagger lists routes, allows developers to try requests, displays endpoint responses, and includes an authentication interface for protected routes. ReDoc documents the same API through a more minimal presentation. These built-in interfaces let developers inspect and test an API without depending entirely on a separate tool such as Postman.

Q: How does Pydantic help a FastAPI application?

Pydantic supports the typing system used by FastAPI, allowing developers to specify expected data types for values such as identifiers and request fields. The course uses Pydantic schemas while progressing from request bodies to database operations. These type definitions also support code completion in VS Code and PyCharm, making application structures easier to write and inspect within those editors.

Q: How do you implement blog CRUD operations with FastAPI?

The course connects FastAPI to a database with SQLAlchemy, defines models, and creates the necessary tables. It then implements operations for storing, retrieving, updating, and deleting blog records. The surrounding API also handles exceptions and status codes, applies response models, and organizes blog logic into routers and repositories as the project is refactored into a larger application structure.

Q: How can FastAPI prevent passwords from appearing in responses?

FastAPI response models can define exactly which fields should appear in returned data. The course uses this capability to restrict user responses so that approved information can be shown without exposing a password. Passwords are also hashed when users are created. Together, password hashing and response filtering address storage and disclosure concerns at different parts of the application workflow.

Q: How is JWT authentication added to a FastAPI API?

The application creates a login route that accepts a username and password, verifies the supplied password against its hashed form, and returns a JWT access token with the bearer type. Selected routes are then placed behind authentication. Swagger can obtain and apply the authentication information, enabling authorized requests to protected blog endpoints after a user successfully logs in.

Q: What happens when a protected FastAPI route is called without authentication?

A protected blog route rejects an unauthenticated request and returns a 401 status code with an unauthorized message. After the user authenticates, the route becomes accessible through the Swagger interface and can return blog data. The returned information can also include creator data produced through the relationship established between the blog and user database models.

Q: How should a larger FastAPI application be structured?

The course begins with code placed wherever it is convenient, then refactors the project as it grows. Routers are created to separate groups such as authentication, blogs, and users, and router parameters and path operations are defined. Blog and user repositories further separate application responsibilities. Documentation tags organize the generated API interface, producing a clearer structure for the completed application.

Summary & Key Takeaways

  • FastAPI is presented as a modern Python framework focused on API development, with asynchronous programming, type hints, editor autocomplete, dependency injection, testing support, and standardized JSON interfaces. It generates interactive Swagger and minimal ReDoc documentation automatically, allowing developers to inspect endpoints, submit requests, review responses, and authenticate without relying on a separate API client.

  • The course builds a blog API from initial installation through database-backed CRUD operations. It covers path and query parameters, request bodies, debugging, Pydantic schemas, SQLAlchemy connections, models, tables, status codes, exceptions, and response models. Response filtering is used to expose selected fields while preventing sensitive information, such as user passwords, from appearing.

  • The completed application includes users, hashed passwords, blog ownership relationships, documentation tags, modular routers, repositories, login verification, JWT access tokens, and authenticated endpoints. Unauthorized requests return a 401 response, while authenticated requests can access protected blog routes and related creator data. The final structured FastAPI application is then deployed using deta.sh.


Read in Other Languages (beta)

Share This Summary 📚

Explore More Summaries from Sarthaksavvy 📚