-
-
Notifications
You must be signed in to change notification settings - Fork 3
✨ fastapi new command
#5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
savannahostrowski
wants to merge
10
commits into
fastapi:main
Choose a base branch
from
savannahostrowski:add-new-command
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+974
−10
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
691f7d2
Initial commit for fastapi new command
savannahostrowski 2793daf
Add mypy
savannahostrowski a1cb214
✅ Add test for entrypoint
savannahostrowski aee9cdd
💡 Remove TODO comment
savannahostrowski 2154504
✅ Remove fixture
savannahostrowski a0c1c9d
💚 Add uv to test-redistribute.yml
savannahostrowski 762e471
♻️ Use --bare and add explicit support for --python
savannahostrowski 43f7416
♻️ Refactor version validation to be simpler
savannahostrowski fda0dec
♻️ Address PR comments from tiangolo
savannahostrowski c87728d
💡 Update comment
savannahostrowski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,32 @@ | ||
| # Python-generated files | ||
| # Python | ||
| __pycache__/ | ||
| *.py[oc] | ||
| *.py[cod] | ||
| *$py.class | ||
| *.so | ||
|
|
||
| # Distribution / packaging | ||
| build/ | ||
| dist/ | ||
| wheels/ | ||
| *.egg-info | ||
| *.egg-info/ | ||
| *.egg | ||
|
|
||
| # Testing / coverage | ||
| htmlcov/ | ||
| .coverage | ||
| .coverage.* | ||
| coverage/ | ||
| .pytest_cache/ | ||
|
|
||
| # Type checking | ||
| .mypy_cache/ | ||
|
|
||
| # Virtual environments | ||
| .venv | ||
|
|
||
| # Coverage | ||
| htmlcov | ||
| .coverage* | ||
| # IDE | ||
| .vscode/ | ||
| .idea/ | ||
|
|
||
| # OS | ||
| .DS_Store | ||
| Thumbs.db |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from .cli import main | ||
|
|
||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import typer | ||
|
|
||
| from fastapi_new.new import new as new_command | ||
|
|
||
| app = typer.Typer(rich_markup_mode="rich") | ||
|
|
||
| app.command()(new_command) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| app() |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,249 @@ | ||
| import pathlib | ||
| import shutil | ||
| import subprocess | ||
| from dataclasses import dataclass | ||
| from typing import Annotated | ||
|
|
||
| import typer | ||
| from rich_toolkit import RichToolkit | ||
|
|
||
| from .utils.cli import get_rich_toolkit | ||
|
|
||
| TEMPLATE_CONTENT = """from fastapi import FastAPI | ||
| app = FastAPI() | ||
|
|
||
| @app.get("/") | ||
| def main(): | ||
| return {"message": "Hello World"} | ||
| """ | ||
|
|
||
|
|
||
| @dataclass | ||
| class ProjectConfig: | ||
| name: str | ||
| path: pathlib.Path | ||
| python: str | None = None | ||
|
|
||
|
|
||
| def _generate_readme(project_name: str) -> str: | ||
| return f"""# {project_name} | ||
|
|
||
| A project created with FastAPI CLI. | ||
|
|
||
| ## Quick Start | ||
|
|
||
| ### Start the development server: | ||
|
|
||
| ```bash | ||
| uv run fastapi dev | ||
| ``` | ||
|
|
||
| Visit http://localhost:8000 | ||
|
|
||
| ### Deploy to FastAPI Cloud: | ||
|
|
||
| > Reader's note: These commands are not quite ready for prime time yet, but will be soon! Join the waiting list at https://fastapicloud.com! | ||
|
|
||
| ```bash | ||
| uv run fastapi login | ||
| uv run fastapi deploy | ||
| ``` | ||
|
|
||
| ## Project Structure | ||
|
|
||
| - `main.py` - Your FastAPI application | ||
| - `pyproject.toml` - Project dependencies | ||
|
|
||
| ## Learn More | ||
|
|
||
| - [FastAPI Documentation](https://fastapi.tiangolo.com) | ||
| - [FastAPI Cloud](https://fastapicloud.com) | ||
| """ | ||
|
|
||
|
|
||
| def _exit_with_error(toolkit: RichToolkit, error_msg: str) -> None: | ||
| toolkit.print(f"[bold red]Error:[/bold red] {error_msg}", tag="error") | ||
| raise typer.Exit(code=1) | ||
|
|
||
|
|
||
| def _validate_python_version(python: str | None) -> str | None: | ||
| """ | ||
| Validate Python version is >= 3.10. | ||
| Returns error message if < 3.10, None otherwise. | ||
| Let uv handle malformed versions or versions it can't find. | ||
| """ | ||
| if not python: | ||
| return None | ||
|
|
||
| try: | ||
| parts = python.split(".") | ||
| if len(parts) < 2: | ||
| return None # Let uv handle malformed version | ||
| major, minor = int(parts[0]), int(parts[1]) | ||
|
|
||
| if major < 3 or (major == 3 and minor < 10): | ||
| return f"Python {python} is not supported. FastAPI requires Python 3.10 or higher." | ||
| except (ValueError, IndexError): | ||
| # Malformed version - let uv handle the error | ||
| pass | ||
|
|
||
| return None | ||
|
|
||
|
|
||
| def _setup(toolkit: RichToolkit, config: ProjectConfig) -> None: | ||
| error = _validate_python_version(config.python) | ||
| if error: | ||
| _exit_with_error(toolkit, error) | ||
|
|
||
| msg = "Setting up environment with uv" | ||
|
|
||
| if config.python: | ||
| msg += f" (Python {config.python})" | ||
|
|
||
| toolkit.print(msg, tag="env") | ||
|
|
||
| # If config.name is provided, create in subdirectory; otherwise init in current dir | ||
| # uv will infer the project name from the directory name | ||
| if config.path == pathlib.Path.cwd(): | ||
| init_cmd = ["uv", "init", "--bare"] | ||
| else: | ||
| init_cmd = ["uv", "init", "--bare", config.name] | ||
|
|
||
| if config.python: | ||
| init_cmd.extend(["--python", config.python]) | ||
|
|
||
| try: | ||
| subprocess.run(init_cmd, check=True, capture_output=True) | ||
| except subprocess.CalledProcessError as e: | ||
| stderr = e.stderr.decode() if e.stderr else "No details available" | ||
| _exit_with_error(toolkit, f"Failed to initialize project with uv. {stderr}") | ||
|
|
||
|
|
||
| def _install_dependencies(toolkit: RichToolkit, config: ProjectConfig) -> None: | ||
| toolkit.print("Installing dependencies...", tag="deps") | ||
|
|
||
| try: | ||
| subprocess.run( | ||
| ["uv", "add", "fastapi[standard]"], | ||
| check=True, | ||
| capture_output=True, | ||
| cwd=config.path, | ||
| ) | ||
| except subprocess.CalledProcessError as e: | ||
| stderr = e.stderr.decode() if e.stderr else "No details available" | ||
| _exit_with_error(toolkit, f"Failed to install dependencies. {stderr}") | ||
|
|
||
|
|
||
| def _write_template_files(toolkit: RichToolkit, config: ProjectConfig) -> None: | ||
| toolkit.print("Writing template files...", tag="template") | ||
| readme_content = _generate_readme(config.name) | ||
|
|
||
| try: | ||
| (config.path / "main.py").write_text(TEMPLATE_CONTENT) | ||
| (config.path / "README.md").write_text(readme_content) | ||
| except Exception as e: | ||
| _exit_with_error(toolkit, f"Failed to write template files. {str(e)}") | ||
|
|
||
|
|
||
| def new( | ||
| ctx: typer.Context, | ||
| project_name: Annotated[ | ||
| str | None, | ||
| typer.Argument( | ||
| help="The name of the new FastAPI project. If not provided, initializes in the current directory.", | ||
| ), | ||
| ] = None, | ||
| python: Annotated[ | ||
| str | None, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm realizing we can require Python 3.10+ for running |
||
| typer.Option( | ||
| "--python", | ||
| "-p", | ||
| help="Specify the Python version for the new project (e.g., 3.14). Must be 3.10 or higher.", | ||
| ), | ||
| ] = None, | ||
| ) -> None: | ||
| if project_name: | ||
| name = project_name | ||
| path = pathlib.Path.cwd() / project_name | ||
| else: | ||
| name = pathlib.Path.cwd().name | ||
| path = pathlib.Path.cwd() | ||
|
|
||
| config = ProjectConfig( | ||
| name=name, | ||
| path=path, | ||
| python=python, | ||
| ) | ||
|
|
||
| with get_rich_toolkit() as toolkit: | ||
| toolkit.print_title("Creating a new project 🚀", tag="FastAPI") | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| if not project_name: | ||
| toolkit.print( | ||
| f"[yellow]⚠️ No project name provided. Initializing in current directory: {path}[/yellow]", | ||
| tag="warning", | ||
| ) | ||
| toolkit.print_line() | ||
|
|
||
| # Check if project directory already exists (only for new subdirectory) | ||
| if project_name and config.path.exists(): | ||
| _exit_with_error(toolkit, f"Directory '{project_name}' already exists.") | ||
|
|
||
| if shutil.which("uv") is None: | ||
| _exit_with_error( | ||
| toolkit, | ||
| "uv is required to create new projects. Install it from https://docs.astral.sh/uv/getting-started/installation/", | ||
| ) | ||
|
|
||
| _setup(toolkit, config) | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| _install_dependencies(toolkit, config) | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| _write_template_files(toolkit, config) | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| # Print success message | ||
| if project_name: | ||
| toolkit.print( | ||
| f"[bold green]✨ Success![/bold green] Created FastAPI project: [cyan]{project_name}[/cyan]", | ||
| tag="success", | ||
| ) | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| toolkit.print("[bold]Next steps:[/bold]") | ||
| toolkit.print(f" [dim]$[/dim] cd {project_name}") | ||
| toolkit.print(" [dim]$[/dim] uv run fastapi dev") | ||
| else: | ||
| toolkit.print( | ||
| "[bold green]✨ Success![/bold green] Initialized FastAPI project in current directory", | ||
| tag="success", | ||
| ) | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| toolkit.print("[bold]Next steps:[/bold]") | ||
| toolkit.print(" [dim]$[/dim] uv run fastapi dev") | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| toolkit.print("Visit [blue]http://localhost:8000[/blue]") | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| toolkit.print("[bold]Deploy to FastAPI Cloud:[/bold]") | ||
| toolkit.print(" [dim]$[/dim] uv run fastapi login") | ||
| toolkit.print(" [dim]$[/dim] uv run fastapi deploy") | ||
|
|
||
| toolkit.print_line() | ||
|
|
||
| toolkit.print( | ||
| "[dim]💡 Tip: Use 'uv run' to automatically use the project's environment[/dim]" | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import logging | ||
|
|
||
| from rich_toolkit import RichToolkit, RichToolkitTheme | ||
| from rich_toolkit.styles import MinimalStyle, TaggedStyle | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class FastAPIStyle(TaggedStyle): | ||
| def __init__(self, tag_width: int = 11): | ||
| super().__init__(tag_width=tag_width) | ||
|
|
||
|
|
||
| def get_rich_toolkit(minimal: bool = False) -> RichToolkit: | ||
| style = MinimalStyle() if minimal else FastAPIStyle(tag_width=11) | ||
|
|
||
| theme = RichToolkitTheme( | ||
| style=style, | ||
| theme={ | ||
| "tag.title": "white on #009485", | ||
| "tag": "white on #007166", | ||
| "placeholder": "grey85", | ||
| "text": "white", | ||
| "selected": "#007166", | ||
| "result": "grey85", | ||
| "progress": "on #007166", | ||
| "error": "red", | ||
| }, | ||
| ) | ||
|
|
||
| return RichToolkit(theme=theme) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| # Tests for fastapi-new |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.